我有一个名为interval的全局变量,我需要在一个函数内部将此全局变量更改为5000,因此在等待1秒后,setInterval函数现在将等待5秒。但是,当我尝试下面的代码时,每次执行仅等待1秒钟。
var timeToWait1 = 1000;
var timeToWait2 = 5000;
var interval = timeToWait1;
setInterval(function(){ waitFunction () }, interval);
function waitFunction() {
interval = timeToWait2;
} //end of function waitFunction()
答案 0 :(得分:1)
时间间隔已设置一次且无法更改,您需要超时。
var timeToWait1 = 1000;
var timeToWait2 = 5000;
setTimeout(waitFunction, timeToWait1);
function waitFunction() {
console.log('waitFunction called');
setTimeout(waitFunction, timeToWait2);
}
答案 1 :(得分:0)
间隔开始后,您将无法更改其使用的持续时间。您必须停止间隔并以新的持续时间重新开始。
let intervalId;
let makeInterval = duration => {
console.log('making a new interval');
intervalId = setInterval(waitFunction, duration);
};
makeInterval(1000);
function waitFunction() {
clearInterval(intervalId);
console.log('waitFunction running');
makeInterval(5000);
}
您可以考虑改用递归setTimeout
,以避免需要清除:
let makeTimeout = duration => {
console.log('making a new timeout');
setTimeout(waitFunction, duration);
};
makeTimeout(1000);
function waitFunction() {
console.log('waitFunction running');
makeTimeout(5000);
}