[英]Stop recursive setTimeout function
我正在運行遞歸setTimeout函數,並且我可以運行多次,它具有clearTimeout,使用此屬性,我可以處理如何停止函數運行。 但是我不知道如何在另一個函數中停止它。
var a = 0;
var b = 0;
function Listener(x, y) {
var lValue = y == true ? a : b;
if (lValue < 100) {
console.log(lValue);
if(y == true){
a+=x;
}else{
b+=x;
}
setTimeout(Listener.bind(this, x, y), 1000);
} else {
clearTimeout(Listener);
if(y == true){
a=0;
}else{
b=0;
}
}
}
當我嘗試運行兩次時,它可以工作:
我的疑問是:如何停止特定正在運行的實例。
幾個注意事項:
1000
的恆定超時,您應該改用setInterval()
。 這將大大簡化您的功能,並允許您隨時取消間隔。 這是結合了這兩個建議的解決方案:
function range (step, start = 0, stop = 100) { const state = { value: start, interval: setInterval(callback, 1000) }; function callback () { if (state.value < stop) { console.log(state.value); state.value += step; } else { console.log('timer done'); clearInterval(state.interval); } } callback(); return state; } const timer1 = range(10); const timer2 = range(20); setTimeout(() => { console.log('stopping timer 1'); clearInterval(timer1.interval); }, 2500); setTimeout(() => { console.log('timer 2 value:', timer2.value); }, 3500);
您可以將計時器提升到其他功能可以訪問的更高范圍。
var a = 0; var b = 0; var timer = null; function Listener(x, y) { var lValue = y == true ? a : b; if (lValue < 100) { console.log(lValue); if (y == true) { a += x; } else { b += x; } timer = setTimeout(Listener.bind(this, x, y), 1000); } else { clearTimeout(timer); if (y == true) { a = 0; } else { b = 0; } } } function clearTimer() { if (timer !== null) clearTimeout(timer); } Listener(3, 3); // clear the timer after 3 secnods setTimeout(clearTimer, 3000);
創建一個變量並將setTimout的引用存儲在該變量上,之后,您只需使用該變量引用清除clear
前
全球變量:
var k = setTimeout(() => { alert(1)}, 10000)
clearTimeout(k)
var a = 0;
var b = 0;
var recursiveFunctionTimeout = null;
function Listener(x, y) {
var lValue = y == true ? a : b;
if (lValue < 100) {
console.log(lValue);
if(y == true){
a+=x;
}else{
b+=x;
}
recursiveFunctionTimeout = setTimeout(Listener.bind(this, x, y), 10);
} else {
clearTimeout(recursiveFunctionTimeout);
if(y == true){
a=0;
}else{
b=0;
}
}
}
局部變量:
var a = 0;
var b = 0;
function Listener(x, y) {
var lValue = y == true ? a : b;
var recursiveFunctionTimeout = null;
if (lValue < 100) {
console.log(lValue);
if(y == true){
a+=x;
}else{
b+=x;
}
recursiveFunctionTimeout = setTimeout(Listener.bind(this, x, y), 10);
} else {
clearTimeout(recursiveFunctionTimeout);
if(y == true){
a=0;
}else{
b=0;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.