阻止在JavaScript中每X秒调用一次函数的最简单方法是什么?

时间:2019-04-30 12:14:40

标签: javascript jquery

我一直在寻找可以解决问题的隔音解决方案,但找不到很多这样的问题。

我的move函数在图块上的每次单击都会被调用,我想阻止用户在当前运动时移动,以阻止重叠的执行错误。

功能如下:

move: function(steps){
    for (var stepx in steps) {
      window.setTimeout(. . ., 300 * stepx);
    }
}

进行迭代,在每次调用该函数时增加300ms的时间。如果是 5步,它将在 1.5秒后完成。

但是,当用户单击两次时,它会设置一组并行的处理程序,这些处理程序会将用户从两个区域中干扰:原始路径和次要路径。

是否可以阻止执行或将超时排队?

2 个答案:

答案 0 :(得分:1)

您只需要将超时保存到变量并调用clearTimeout()-但是,您的示例在循环中创建了多个超时,因此您需要先保存所有超时然后停止所有超时。可以这样完成:

var timers = [];
var running = false;

function makeSteps(steps) {
  if (!running) {
    running = true;
    for (var i = 0; i <= steps; i++) {
      timers.push(setTimeout(function() {
        console.log("Step");
      }, 300 * i));
    }
  }
}

function stopAllSteps() {
  for (var i = 0; i <= timers.length; i++) {
    clearTimeout(timers[i]);
  }
  running = false;
  console.log("stopped!");
}
<button type="button" onclick="makeSteps(100)">Start</button>
<button type="button" onclick="stopAllSteps()">Stop</button>

答案 1 :(得分:0)

您可以使用变量来阻止用户点击,直到完成为止。

如果我很了解您的要求。

let inProgress = false;

function clickFunc(steps) {
  console.log('The user clicked');

  if (inProgress) {
    console.log('Action already in progress');

    return;
  }

  inProgress = true;

  for (let i = 0; i < steps; i += 1) {
    window.setTimeout(() => {
      // if the last step is over, we stop the click block
      if (i === steps - 1) {
        inProgress = false;
      }

      console.log('One step done');
    }, 300 * i);
  }
}
.button {
  height: 2em;
  width: 10em;
  background-color: #444444;
  color: white;
  cursor: pointer;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}

.button:hover {
  opacity: 0.9;
}
<div class="button" onclick="clickFunc(3)">Button</div>