Javascript间隔持续不断,没有满足条件 [英] Javascript Interval continues endless without conditions met

查看:66
本文介绍了Javascript间隔持续不断,没有满足条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var counter;
var count = 0;

var equalsPressed = false;
var dritter = false;
var array = new Array();

window.onload = function() {
  let x = document.getElementsByClassName('zahlen')
  let i;
  for (i = 0; i < x.length; i++) {
    let y = x[i];
    x[i].addEventListener('mousedown', function() {
      add(this.className, this.value.replace(/\s/g, ''));
    }, true);
    //x[i].addEventListener(mousedown,function('Hi')
    x[i].onmousedown = debounce(function() {
      start(y.className, y.value.replace(/\s/g, ''));
    }, 200);
  }
}

function debounce(a, b) {
  return function() {
    let timer;
    clearTimeout(timer);
    booli = true;
    timer = setTimeout(function() {
      if (booli) {
        a();
      } else {
        clearInterval(counter);
      }
    }, b);
  };
}


function start(clicked_className, Zeichen) {
  counter = setInterval(function() {
    add(clicked_className, Zeichen);
    count++;
  }, 370);
}

function end() {
  booli = false;
  clearInterval(counter);
}


function Check(Eingabe) {
  // indexof=suche in "0123456789[]()-+*%/" nach den chars der eingabe(0 bis 1 kleiner als länge (also alle)) und schaue an welcher position im string diese sind.wenn position kleiner0(also nicht vorhanden)
  // dann return false, ansonsten alles gut
  var inhalt = "0123456789[]().-+*%/=e";
  for (var i = 0; i < Eingabe.length; i++)
    if (inhalt.indexOf(Eingabe.charAt(i)) < 0) return false;
  return true;
}


function Ergebnis() {
  var z = document.getElementById("Historie");
  z.style.display = "block";
  var ausg = 0;

  if (equalsPressed && Check(window.document.Rechner.Display.value)) {
    var o = window.document.Rechner.Display2.value;
    var p = window.document.Rechner.Display.value;
    p = p.replace("=", '');

    const chars = ["+", "-", "*", "/"];
    var last;

    for (const rechenarten of o) {
      if (chars.includes(rechenarten)) {
        last = rechenarten;
      }

    }
    //lastIndexOf zählt von hinten und fängt bei o.length - 1 also der letzten Position an
    //und sucht last, also die am weitesten hinten vorkommende der Rechenarten
    o = o.slice(o.lastIndexOf(last, o.length - 1), o.lenght);

    ausg = eval(p + o);

    ausg = ausg.toFixed(getDecimalPlaces(p));
    window.document.Rechner.Display.value = ausg;
    window.document.Rechner.Display2.value = window.document.Rechner.Display2.value + o;
    dritter = true;
  } else {
    var y = 0;
    var x = 0;

    if (Check(window.document.Rechner.Display.value))
      y = window.document.Rechner.Display.value;
    window.document.Rechner.Display2.value = y;
    ausg = eval(window.document.Rechner.Display.value);
    ausg = ausg.toFixed(getDecimalPlaces(y)); //
    window.document.Rechner.Display.value = "=" + ausg;
  }
}

function getDecimalPlaces(numb) {
  var highest = 0;
  var counter = 0;
  for (a = 0; a < numb.length; a++) {
    if (numb.charAt(a - 1) == ".") {
      do {
        counter++;
        a++;
      }
      while (!isNaN(numb.charAt(a)) && a < numb.length);
    }
    if (counter > highest) {
      highest = counter;
    }
    counter = 0;
  }
  return highest;
}


function add(clicked_className, Zeichen) {
  if (equalsPressed == false && clicked_className == 'zahlen') {
    window.document.Rechner.Display.value =
      window.document.Rechner.Display.value + Zeichen;
  } else if (dritter && equalsPressed && clicked_className == 'zahlen') {
    var array = new Array();
    array.push(window.document.Rechner.Display2.value + "=" +
      window.document.Rechner.Display.value);

    var myTableDiv = document.getElementById("Historie")
    var table = document.createElement('TABLE')
    var tableBody = document.createElement('TBODY')
    table.border = '0';
    table.appendChild(tableBody);
    var tr = document.createElement('TR');
    tableBody.appendChild(tr);

    var td = document.createElement('TD')
    td.width = '275';
    td.style.textAlign = "right";
    td.appendChild(document.createTextNode(array[0]));

    tr.appendChild(td);
    myTableDiv.appendChild(table)


    window.document.Rechner.Display2.value = "";
    window.document.Rechner.Display.value = "";
    window.document.Rechner.Display.value =
      window.document.Rechner.Display.value + Zeichen;
    equalsPressed = false;

  } else if (equalsPressed && clicked_className == 'zahlen') {
    window.document.Rechner.Display2.value = "";
    window.document.Rechner.Display.value = "";
    window.document.Rechner.Display.value =
      window.document.Rechner.Display.value + Zeichen;
    equalsPressed = false;

  } else if (clicked_className == 'ops') {
    var x;
    window.document.Rechner.Display.value = window.document.Rechner.Display.value.replace("=", '');
    window.document.Rechner.Display.value =
      window.document.Rechner.Display.value + Zeichen;
    equalsPressed = false;
  }
}



function gleichPressed() {
  equalsPressed = true;
}


function backspace() {
  var abschneiden = window.document.Rechner.Display.value;
  for (var i = 0; i < abschneiden.length; i++) {
    var output = abschneiden.slice(0, -1);
    window.document.Rechner.Display.value = output;
  }
}

function ausgabe() {

  if (equalsPressed) {

  } else {

    array.push(window.document.Rechner.Display2.value +
      window.document.Rechner.Display.value);
    console.log(array);

    var myTableDiv = document.getElementById("Historie")
    var table = document.createElement('TABLE')
    var tableBody = document.createElement('TBODY')
    table.border = '0';
    table.appendChild(tableBody);
    var tr = document.createElement('TR');
    tableBody.appendChild(tr);

    var td = document.createElement('TD')
    td.width = '275';
    td.style.textAlign = "right";
    td.appendChild(document.createTextNode(array[0]));

    tr.appendChild(td);
    myTableDiv.appendChild(table)
  }
}

body {
  font-family: "Century Gothic", CenturyGothic, Geneva, AppleGothic, sans-serif;
}

.button,
.ops,
.zahlen,
.sonst,
.istgleich {
  background-color: #A4A4A4;
  background: linear-gradient(240deg, grey, white);
  color: black;
  width: 60px;
  text-align: center;
  font-family: System, sans-serif;
  font-size: 100%;
}

.button:hover,
.zahlen:hover,
.sonst:hover,
.ops:hover,
.istgleich:hover {
  color: #2E2E2E;
  background-color: #FAFAFA;
  background: linear-gradient(30deg, darkgrey, lightgrey, grey);
  ;
}

.display {
  width: 100%;
  text-align: right;
  font-family: System, sans-serif;
  font-size: 100%;
}

#Historie {
  background: linear-gradient(30deg, silver, white, grey);
  ;
  border: 5px outset;
  float: left;
  text-align: right;
}

#eins {
  background: linear-gradient(30deg, silver, grey, DimGray);
  ;
}

#zwei {
  background: linear-gradient(90deg, silver, grey);
  ;
}

#tabelle {
  width: 300px;
  height: 235px;
  float: left;
}

<html onmouseup="end()">

<head>
  <meta charset="UTF-8">
  <title>Taschenrechner</title>
</head>

<body bgcolor="#FFFFE0" text="#000000">
  <form name="Rechner" action="" onSubmit="Ergebnis();return false;">
    <table id="tabelle" style="float:left" border="7" cellpadding="12" cellspacing="0">
      <tr>
        <td id="eins">
          <input type="text" name="Display2" class="display" readonly>
          <input type="text" name="Display" class="display" readonly></td>
      </tr>

      <tr>
        <td id="zwei">

          <table border="1" cellpadding="0" cellspacing="0">
            <tr>
              <td><input type="button" class="zahlen" value="  7   " onmouseleave="end()">
              </td>
              <td><input type="button" class="zahlen" value="  8   " onmouseleave="end()">
              </td>
              <td><input type="button" class="zahlen" value="  9   " onmouseleave="end()">
              </td>
              <td><input type="button" class="sonst" value="  &#171  " onClick="backspace()">
              </td>
            </tr>

            <tr>
              <td><input type="button" class="zahlen" value="  4   " onmouseleave="end()">
              </td>
              <td><input type="button" class="zahlen" value="  5   " onmouseleave="end()">
              </td>
              <td><input type="button" class="zahlen" value="  6   " onmouseleave="end()">
              </td>
              <td><input type="button" class="ops" value="  +   " onClick="add(this.className,'+')">
              </td>
            </tr>

            <tr>
              <td><input type="button" class="zahlen" value="  1   " onmouseleave="end()">
              </td>
              <td><input type="button" class="zahlen" value="  2   " onmouseleave="end()">
              </td>
              <td><input type="button" class="zahlen" value="  3   " onmouseleave="end()">
              </td>
              <td><input type="button" class="ops" value="  -   " onClick="add(this.className,'-')">
              </td>
            </tr>

            <tr>
              <td><input type="button" class="zahlen" value="  .   ">
              </td>
              <td><input type="button" class="zahlen" value="  0   " onmouseleave="end()">
              </td>
              <td><input type="button" class="istgleich" value="  =   " onClick="Ergebnis();ausgabe();gleichPressed()">
              </td>
              <td><input type="button" class="ops" value="  *   " onClick="add(this.className,'*')">
              </td>
            </tr>

            <tr>
              <td><input type="button" class="zahlen" value=" ( ">
              </td>
              <td><input type="button" class="zahlen" value=" ) ">
              </td>
              <td><input type="reset" class="button" value="  C  ">
              </td>
              <td><input type="button" class="ops" value="  /   " onClick="add(this.className,'/')">
              </td>
            </tr>

          </table>
        </td>
      </tr>
    </table>
  </form>

  <div class="Historie" id="Historie" hidden="true">
  </div>
</body>

</html>

说明__:双击并按住

我真的很无助地发现该错误试图找到它的起源,并建立了几个布尔值,因此循环仅在它们为true时才运行,而它们全都是false,并且仍然继续运行.

Im really really helpless in finding that bug tried to find where it originates, and build in couple of booleans so the loop only runs if theyre true but they were all false and it still continued running.

我正在寻找解决问题的好方法:(

Im looking for a solution or a good way to adress the problem:(

我发现非常值得注意的是,它仅在快速执行所需的按键时发生,如果执行得较慢,则不会导致该错误,而且多次执行时,也会循环多次.

What i found very noteworthy is that it only occurs when doing the needed keypresses fast, if done slower it doesnt result in that bug, also when done multiple times, it loops multiple times.

推荐答案

就像Bergi所说的那样,您的去抖动功能已损坏.您需要在返回的函数之外初始化timer变量.

Just like Bergi said, your debounce function is broken. You need to initialize the timer variable outside the returned function.

这是您的实现:

function debounce(a, b) {
  return function() {
    let timer;
    clearTimeout(timer);
    booli = true;
    timer = setTimeout(function() {
      if (booli) {
        a();
      } else {
        clearInterval(counter);
      }
    }, b);
  };
}

这是解决错误的方法:

function debounce(a, b) {
  let timer;
  return function() {
    clearTimeout(timer);
    booli = true;
    timer = setTimeout(function() {
      if (booli) {
        a();
      } else {
        clearInterval(counter);
      }
    }, b);
  };
}

var counter;
var count = 0;

var equalsPressed = false;
var dritter = false;
var array = new Array();

window.onload = function() {
  let x = document.getElementsByClassName('zahlen')
  let i;
  for (i = 0; i < x.length; i++) {
    let y = x[i];
    x[i].addEventListener('mousedown', function() {
      add(this.className, this.value.replace(/\s/g, ''));
    }, true);
    //x[i].addEventListener(mousedown,function('Hi')
    x[i].onmousedown = debounce(function() {
      start(y.className, y.value.replace(/\s/g, ''));
    }, 200);
  }
}

function debounce(a, b) {
  let timer;
  return function() {
    clearTimeout(timer);
    booli = true;
    timer = setTimeout(function() {
      if (booli) {
        a();
      } else {
        clearInterval(counter);
      }
    }, b);
  };
}


function start(clicked_className, Zeichen) {
  counter = setInterval(function() {
    add(clicked_className, Zeichen);
    count++;
  }, 370);
}

function end() {
  booli = false;
  clearInterval(counter);
}


function Check(Eingabe) {
  // indexof=suche in "0123456789[]()-+*%/" nach den chars der eingabe(0 bis 1 kleiner als länge (also alle)) und schaue an welcher position im string diese sind.wenn position kleiner0(also nicht vorhanden)
  // dann return false, ansonsten alles gut
  var inhalt = "0123456789[]().-+*%/=e";
  for (var i = 0; i < Eingabe.length; i++)
    if (inhalt.indexOf(Eingabe.charAt(i)) < 0) return false;
  return true;
}


function Ergebnis() {
  var z = document.getElementById("Historie");
  z.style.display = "block";
  var ausg = 0;

  if (equalsPressed && Check(window.document.Rechner.Display.value)) {
    var o = window.document.Rechner.Display2.value;
    var p = window.document.Rechner.Display.value;
    p = p.replace("=", '');

    const chars = ["+", "-", "*", "/"];
    var last;

    for (const rechenarten of o) {
      if (chars.includes(rechenarten)) {
        last = rechenarten;
      }

    }
    //lastIndexOf zählt von hinten und fängt bei o.length - 1 also der letzten Position an
    //und sucht last, also die am weitesten hinten vorkommende der Rechenarten
    o = o.slice(o.lastIndexOf(last, o.length - 1), o.lenght);

    ausg = eval(p + o);

    ausg = ausg.toFixed(getDecimalPlaces(p));
    window.document.Rechner.Display.value = ausg;
    window.document.Rechner.Display2.value = window.document.Rechner.Display2.value + o;
    dritter = true;
  } else {
    var y = 0;
    var x = 0;

    if (Check(window.document.Rechner.Display.value))
      y = window.document.Rechner.Display.value;
    window.document.Rechner.Display2.value = y;
    ausg = eval(window.document.Rechner.Display.value);
    ausg = ausg.toFixed(getDecimalPlaces(y)); //
    window.document.Rechner.Display.value = "=" + ausg;
  }
}

function getDecimalPlaces(numb) {
  var highest = 0;
  var counter = 0;
  for (a = 0; a < numb.length; a++) {
    if (numb.charAt(a - 1) == ".") {
      do {
        counter++;
        a++;
      }
      while (!isNaN(numb.charAt(a)) && a < numb.length);
    }
    if (counter > highest) {
      highest = counter;
    }
    counter = 0;
  }
  return highest;
}


function add(clicked_className, Zeichen) {
  if (equalsPressed == false && clicked_className == 'zahlen') {
    window.document.Rechner.Display.value =
      window.document.Rechner.Display.value + Zeichen;
  } else if (dritter && equalsPressed && clicked_className == 'zahlen') {
    var array = new Array();
    array.push(window.document.Rechner.Display2.value + "=" +
      window.document.Rechner.Display.value);

    var myTableDiv = document.getElementById("Historie")
    var table = document.createElement('TABLE')
    var tableBody = document.createElement('TBODY')
    table.border = '0';
    table.appendChild(tableBody);
    var tr = document.createElement('TR');
    tableBody.appendChild(tr);

    var td = document.createElement('TD')
    td.width = '275';
    td.style.textAlign = "right";
    td.appendChild(document.createTextNode(array[0]));

    tr.appendChild(td);
    myTableDiv.appendChild(table)


    window.document.Rechner.Display2.value = "";
    window.document.Rechner.Display.value = "";
    window.document.Rechner.Display.value =
      window.document.Rechner.Display.value + Zeichen;
    equalsPressed = false;

  } else if (equalsPressed && clicked_className == 'zahlen') {
    window.document.Rechner.Display2.value = "";
    window.document.Rechner.Display.value = "";
    window.document.Rechner.Display.value =
      window.document.Rechner.Display.value + Zeichen;
    equalsPressed = false;

  } else if (clicked_className == 'ops') {
    var x;
    window.document.Rechner.Display.value = window.document.Rechner.Display.value.replace("=", '');
    window.document.Rechner.Display.value =
      window.document.Rechner.Display.value + Zeichen;
    equalsPressed = false;
  }
}



function gleichPressed() {
  equalsPressed = true;
}


function backspace() {
  var abschneiden = window.document.Rechner.Display.value;
  for (var i = 0; i < abschneiden.length; i++) {
    var output = abschneiden.slice(0, -1);
    window.document.Rechner.Display.value = output;
  }
}

function ausgabe() {

  if (equalsPressed) {

  } else {

    array.push(window.document.Rechner.Display2.value +
      window.document.Rechner.Display.value);
    console.log(array);

    var myTableDiv = document.getElementById("Historie")
    var table = document.createElement('TABLE')
    var tableBody = document.createElement('TBODY')
    table.border = '0';
    table.appendChild(tableBody);
    var tr = document.createElement('TR');
    tableBody.appendChild(tr);

    var td = document.createElement('TD')
    td.width = '275';
    td.style.textAlign = "right";
    td.appendChild(document.createTextNode(array[0]));

    tr.appendChild(td);
    myTableDiv.appendChild(table)
  }
}

body {
  font-family: "Century Gothic", CenturyGothic, Geneva, AppleGothic, sans-serif;
}

.button,
.ops,
.zahlen,
.sonst,
.istgleich {
  background-color: #A4A4A4;
  background: linear-gradient(240deg, grey, white);
  color: black;
  width: 60px;
  text-align: center;
  font-family: System, sans-serif;
  font-size: 100%;
}

.button:hover,
.zahlen:hover,
.sonst:hover,
.ops:hover,
.istgleich:hover {
  color: #2E2E2E;
  background-color: #FAFAFA;
  background: linear-gradient(30deg, darkgrey, lightgrey, grey);
  ;
}

.display {
  width: 100%;
  text-align: right;
  font-family: System, sans-serif;
  font-size: 100%;
}

#Historie {
  background: linear-gradient(30deg, silver, white, grey);
  ;
  border: 5px outset;
  float: left;
  text-align: right;
}

#eins {
  background: linear-gradient(30deg, silver, grey, DimGray);
  ;
}

#zwei {
  background: linear-gradient(90deg, silver, grey);
  ;
}

#tabelle {
  width: 300px;
  height: 235px;
  float: left;
}

<html onmouseup="end()">

<head>
  <meta charset="UTF-8">
  <title>Taschenrechner</title>
</head>

<body bgcolor="#FFFFE0" text="#000000">
  <form name="Rechner" action="" onSubmit="Ergebnis();return false;">
    <table id="tabelle" style="float:left" border="7" cellpadding="12" cellspacing="0">
      <tr>
        <td id="eins">
          <input type="text" name="Display2" class="display" readonly>
          <input type="text" name="Display" class="display" readonly></td>
      </tr>

      <tr>
        <td id="zwei">

          <table border="1" cellpadding="0" cellspacing="0">
            <tr>
              <td><input type="button" class="zahlen" value="  7   " onmouseleave="end()">
              </td>
              <td><input type="button" class="zahlen" value="  8   " onmouseleave="end()">
              </td>
              <td><input type="button" class="zahlen" value="  9   " onmouseleave="end()">
              </td>
              <td><input type="button" class="sonst" value="  &#171  " onClick="backspace()">
              </td>
            </tr>

            <tr>
              <td><input type="button" class="zahlen" value="  4   " onmouseleave="end()">
              </td>
              <td><input type="button" class="zahlen" value="  5   " onmouseleave="end()">
              </td>
              <td><input type="button" class="zahlen" value="  6   " onmouseleave="end()">
              </td>
              <td><input type="button" class="ops" value="  +   " onClick="add(this.className,'+')">
              </td>
            </tr>

            <tr>
              <td><input type="button" class="zahlen" value="  1   " onmouseleave="end()">
              </td>
              <td><input type="button" class="zahlen" value="  2   " onmouseleave="end()">
              </td>
              <td><input type="button" class="zahlen" value="  3   " onmouseleave="end()">
              </td>
              <td><input type="button" class="ops" value="  -   " onClick="add(this.className,'-')">
              </td>
            </tr>

            <tr>
              <td><input type="button" class="zahlen" value="  .   ">
              </td>
              <td><input type="button" class="zahlen" value="  0   " onmouseleave="end()">
              </td>
              <td><input type="button" class="istgleich" value="  =   " onClick="Ergebnis();ausgabe();gleichPressed()">
              </td>
              <td><input type="button" class="ops" value="  *   " onClick="add(this.className,'*')">
              </td>
            </tr>

            <tr>
              <td><input type="button" class="zahlen" value=" ( ">
              </td>
              <td><input type="button" class="zahlen" value=" ) ">
              </td>
              <td><input type="reset" class="button" value="  C  ">
              </td>
              <td><input type="button" class="ops" value="  /   " onClick="add(this.className,'/')">
              </td>
            </tr>

          </table>
        </td>
      </tr>
    </table>
  </form>

  <div class="Historie" id="Historie" hidden="true">
  </div>
</body>

</html>

这篇关于Javascript间隔持续不断,没有满足条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆