下面是一个例子。
var count,
time = 1000;
setInterval(function(){
count += 1;
}, time);上面的代码将将1添加到"count“var,非常1000毫秒。似乎setInterval在触发时将使用它在执行时所看到的时间。如果稍后更新该值,它将不会考虑到这一点,并将在设置的初始时间内继续启动。
如何动态更改此方法的时间?
发布于 2013-09-23 15:48:37
与回调和变量(而不是数字)一起使用setTimeout。
function timeout() {
setTimeout(function () {
count += 1;
console.log(count);
timeout();
}, time);
};
timeout();Demo 这里
的较短版本是:
function periodicall() {
count++;
setTimeout(periodicall, time);
};
periodicall();发布于 2013-09-23 15:43:02
尝试:
var count,
time = 1000,
intId;
function invoke(){
intId = setInterval(function(){
count += 1;
if(...) // now i need to change my time
{
time = 2000; //some new value
intId = window.clearInterval(intId);
invoke();
}
}, time);
}
invoke();您不能动态地更改时间间隔,因为它只设置了一次,然后就不再重新运行setInterval代码。那么,您可以做什么来清除间隔,并再次将其设置为运行。您也可以使用具有类似逻辑的setTimeout,但使用setTimeout时,每次都需要注册超时,除非您希望在两者之间中止,否则不需要使用clearTimeout。如果你每次都改变时间,那么setTimeout就更有意义了。
var count,
time = 1000;
function invoke() {
count += 1;
time += 1000; //some new value
console.log('displ');
window.setTimeout(invoke, time);
}
window.setTimeout(invoke, time);发布于 2013-09-23 15:43:11
(据我所知)你不能动态地改变间隔。我建议通过回调来做到这一点:
var _time = 1000,
_out,
_count = 0,
yourfunc = function() {
count++;
if (count > 10) {
// stop
clearTimeout(_out); // optional
}
else {
// your code
_time = 1000 + count; // for instance
_out = setTimeout(function() {
yourfunc();
}, _time);
}
};https://stackoverflow.com/questions/18963377
复制相似问题