SetTimeout运行不正常

SetTimeout not functioning properly

本文关键字:不正常 运行 SetTimeout      更新时间:2023-09-26

此代码同时运行所有21个控制台日志。然而,它应该以设定的间隔一次运行一个。有什么建议吗?

var index = 1;
var switchBG = function(num){
    if( num < 22 ){
        console.log('index' + index);
        console.log('num' + num);
        index++;
        function_timer(index);
    }
};
var timer;
var function_timer = function(index){
    clearTimeout(timer);
    timer = setTimeout(switchBG(index), 10000);
};

您需要将函数作为参数传递给setTimeout。试试这个:

timer = setTimeout(function() {
    switchBG(index);
}, 10000);

执行setTimeout(switchBG(index), 10000);基本上评估switchBG(index)并将其返回值(当前为undefined)传递给setTimeout

当你这样做时:

setTimeout(switchBG(index), 10000);

您将立即调用switchBG(index),然后将其返回值(即undefined)传递给setTimeout。相反,您希望传递一个函数引用,然后将附加参数传递给setTimeout:

setTimeout(switchBG, 10000, index);

如果你想像在Internet Explorer中那样使用setTimeout的附加参数,你需要填充它。它可以在没有填充的其他浏览器中工作。

如果你想支持IE,又不想使用填充程序,你可以创建一个额外的匿名函数来实现同样的结果:

setTimeout(function(){ switchBG(index); }, 10000);