这里变量timer在timerIncrement
函数之外声明。由于范围可变,我知道改变函数内部的值不会改变它。但是我真的需要提出这样的事情,这样一旦idleTime > 5
它就会使用新的计时器。
我怎样才能做到这一点?
jQuery(document).ready(function($) {
var timer = 1000;
// //increment the idle time counter every sec.
var idleInterval = setInterval(timerIncrement, timer); // 1 sec
function timerIncrement() {
while(idleTime < 5){
console.log('test '+idleTime);
idleTime = idleTime + 1;
}
timer = 2000;//how to make this take affect on the top so that setInterval run at this newly set timer
console.log('reached max');
}
}
答案 0 :(得分:2)
这应该有效:
function timerIncrement() {
while(idleTime < 5){
console.log('test '+idleTime);
idleTime = idleTime + 1;
}
timer = 2000;//how to make this take affect on the top so that setInterval run at this newly set timer
clearInterval(idleInterval);
idleInterval = setInterval(timerIncrement, timer);
console.log('reached max');
}
答案 1 :(得分:1)
因为在初始调用setInterval
时设置了间隔。修改delay
的值将无效。
您应该在此方案中使用setTimeout
。
$(document).ready(function() {
var timer = 1000;
var idleInterval = setTimeout(timerIncrement, timer); // 1 sec
function timerIncrement() {
timer = 2000
//Recursively call your method
idleInterval = setTimeout(timerIncrement, timer);
}
});