簡體   English   中英

阻止在JavaScript中每X秒調用一次函數的最簡單方法是什么?

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

我一直在尋找解決問題的隔音解決方案,但找不到很多這樣的問題。

我的move功能在圖塊上的每次點擊都被調用,我想阻止用戶在當前運動時移動,以阻止重疊的執行錯誤。

功能如下:

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

進行迭代,在每次將要調用該函數時增加300ms的時間。 如果是5步 ,則將在1.5秒后完成。

但是,當用戶單擊兩次時,它會設置一堆並行的處理程序,這些處理程序會在兩個方面使用戶感到麻煩:原始路徑和次要路徑。

有沒有辦法阻止執行或將超時排隊?

您只需要將超時保存到變量中並調用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> 

您可以使用變量來阻止用戶點擊,直到完成為止。

如果我能很好地理解您的要求。

 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