简体   繁体   English

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

[英]What's the easiest way to stop a function from being called every X seconds in JavaScript?

I've looked around for a soundproof solution to my problem but was not able to find many SO questions like this. 我一直在寻找解决问题的隔音解决方案,但找不到很多这样的问题。

My move function gets called each click on a tile, I want to block the user from moving whilst they are currently in motion to block overlapping execution bugs. 我的move功能在图块上的每次点击都被调用,我想阻止用户在当前运动时移动,以阻止重叠的执行错误。

The functions work as following: 功能如下:

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

Which iterates, adding a forward 300ms to when the function is going to be called each time. 进行迭代,在每次将要调用该函数时增加300ms的时间。 If it's 5 steps , it'll finish after 1.5 seconds . 如果是5步 ,则将在1.5秒后完成。

But, when the user clicks twice it sets up a parallel bunch of handlers that glitch the user from two areas: the original path being travelled and the secondary. 但是,当用户单击两次时,它会设置一堆并行的处理程序,这些处理程序会在两个方面使用户感到麻烦:原始路径和次要路径。

Is there a way to block execution or queue the timeouts? 有没有办法阻止执行或将超时排队?

You just need to save the timeout to a variable and call clearTimeout() - however, your example creates multiple timeouts in a loop, so you'd need to save them all and then stop them all. 您只需要将超时保存到变量中并调用clearTimeout() -但是,您的示例在循环中创建了多个超时,因此您需要先保存所有超时然后停止所有超时。 It could be done like this: 可以这样完成:

 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> 

You could use of a variable to block the user clicks until it gets done. 您可以使用变量来阻止用户点击,直到完成为止。

If I understood well what you asked for. 如果我能很好地理解您的要求。

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM