[英]Why is this simple javascript code not working?
var interval = 250
setInterval(function(){
if ( 1==1 ) {
interval = 5000
}
}, interval)
This should set interval at 5000 if 1 == 1 but it keeps the interval at 250. 如果1 == 1,则应将间隔设置为5000,但将间隔保持为250。
Because interval
in this case is evaluated just once, when setInterval
function is called (note the difference with setInterval
parameter function, which will be called repeatedly). 因为在这种情况下
interval
仅被评估一次,所以在调用setInterval
函数时(请注意与setInterval
参数函数的区别,它将被重复调用)。
To make the interval change after the first run, you can use setTimeout
instead, with something like: 要在第一次运行后更改间隔,可以改用
setTimeout
,例如:
setTimeout(function() {
(function _t() {
// doSomethingUseful();
setTimeout(_t, 5000);
})();
}, 250);
You can't change the interval without calling setInterval all over again. 您必须重新调用setInterval才能更改间隔。 I would use some sort of setTimeout loop instead.
我会改用setTimeout循环。
执行回调函数时,使用250作为参数调用setInterval,并且在函数中更改间隔值时,此更改不会影响先前的设置值。
setInterval将每250 MS调用一次回调,但是setInterval本身将被调用一次
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.