问题
The timing value in setInterval determines the next time at which the function is going to be invoked again. For example:
t = 8000;
myFunction(){
if (someCondition){
//halt setInterval
//t = 5000;
// setInterval(myFunction,t);
}
// do some logic
}
setInterval(myFunction, t);
The problem is changing of t will not affect the time that I want the current call to be remained before the next call. In other words, is there any way to halt setInterval and then I can reset it again with new time?
回答1:
If you want to do something like that, you're better off doing your own interval control with setTimeout.
var shortInterval = 2000, longInterval = 4000;
function timerCode() {
// do something
if (whatever) {
setTimeout(timerCode, shortInterval);
}
else {
setTimeout(timerCode, longInterval);
}
}
setTimeout(timerCode, longInterval);
That way, on each iteration of the timer you can decide how long it should be until the next iteration. If you want to stop, just don't reset the timer at all.
回答2:
You have to use clearInterval().
var myInterval = setInterval(myFunction, t);
...
clearInterval(myInterval);
...
myInterval = setInterval(myFunction, 1000);
来源:https://stackoverflow.com/questions/19801278/temporary-changing-the-time-of-setinterval