clearInterval不会停止间隔

时间:2017-12-20 23:36:11

标签: javascript jquery html

在这里查看同一问题后,我无法找到解决问题的方法。我所拥有的是以下问题

function movement(mov, element) {
  canvasMov = document.getElementById('xy_canvas');
  ctxMov = canvasMov.getContext("2d");
  wMov = canvasMov.width;
  hMov = canvasMov.height;
  if (element != 'xy_canvas') {
    my_range = document.getElementById(element);
    if (mov) {
      my_interval = setInterval(function() {
        if (my_range != null)
          touchEvents(my_range.value);
        sendMovements(element);
      }, 160);
    } else {
      clearInterval(my_interval);
      console.log(element, mov);
      my_range.value = 0;
    }
    if (my_range.value == 0)
      clearInterval(my_interval);
  } else {
    if (mov) {
      my_interval = setInterval(function() {
        eventsMove();
        sendMovements();
      }, 160);
    } else {
      clearInterval(my_interval);
      console.log(element, mov);
    }

  }
}
<div class="col12 fl">
  <input type="range" id="alt_range" min="-1" max="1" value="0" step="0.2" class="slider" oninput="movement(true,'alt_range')" onmouseup="movement(false,'alt_range')">
</div>

clearInterval没有停止间隔,也许我在这里遗漏了什么,有什么建议吗?

2 个答案:

答案 0 :(得分:2)

当您开始新的间隔功能时,您不会停止旧的间隔功能。然后clearInterval(my_interval)将仅停止最后一个已启动的,但较旧的将继续运行。您需要在每次clearInterval(my_interval);来电之前致电setInterval()

由于代码中的所有路径最终都会调用setInterval()clearInterval(),因此您只需在函数开头执行一次clearInterval(my_interval)

&#13;
&#13;
function movement(mov, element) {
  canvasMov = document.getElementById('xy_canvas');
  ctxMov = canvasMov.getContext("2d");
  wMov = canvasMov.width;
  hMov = canvasMov.height;
  clearInterval(my_interval)
  if (element != 'xy_canvas') {
    my_range = document.getElementById(element);
    if (mov) {
      if (my_range.value != 0) {
        my_interval = setInterval(function() {
          if (my_range != null)
            touchEvents(my_range.value);
          sendMovements(element);
        }, 160);
      }
    } else {
      console.log(element, mov);
      my_range.value = 0;
    }
  } else {
    if (mov) {
      my_interval = setInterval(function() {
        eventsMove();
        sendMovements();
      }, 160);
    } else {
      console.log(element, mov);
    }

  }
}
&#13;
<div class="col12 fl">
  <input type="range" id="alt_range" min="-1" max="1" value="0" step="0.2" class="slider" oninput="movement(true,'alt_range')" onmouseup="movement(false,'alt_range')">
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您需要做的就是在顶部定义my_interval,例如

var my_interval = null;

目前,您正在my_interval条件中创建if,其余代码会隐藏它。