setTimeout不符合我在$.each中给它的延迟值

setTimeout is not staying true to the delay I give it inside a $.each

本文关键字:延迟 each 不符合 setTimeout      更新时间:2023-09-26

给定以下代码:

counter = 0;
$('div').each(function () {
    counter++;
    console.log(counter + ': Timeout is: ' + $(this).index() * 150);
    setTimeout(testTime(), $(this).index() * 150);
});
function testTime() {
    var currentDate = new Date();
    console.log(counter + ': Call time is: ' + currentDate.getMilliseconds());
}

如果您查看控制台日志,您可以看到它被调用的毫秒数和每次调用之间的假定延迟。正如您所看到的,每次调用之间只有几毫秒的间隔。

setTimeout的第一个参数应该是一个函数。

调用 testTime并传递其返回值(undefined)作为参数。

去除()

更新响应注释:

如果你需要传递参数,那么你需要将它们作为第三个参数在数组中传递(根据文档),或者为了更广泛的浏览器支持,使用闭包。

counter = 0;
$('div').each(function () {
    counter++;
    console.log(counter + ': Timeout is: ' + $(this).index() * 150);
    setTimeout(testTimeFactory(foo, bar, baz), $(this).index() * 150);
});
function testTime() {
    var currentDate = new Date();
    console.log(counter + ': Call time is: ' + currentDate.getMilliseconds());
}
function testTimeFactory(a, b, c) {
    return function() {
        testTime(a, b, c);
    }
}

在您的代码中,您在超时时立即调用该函数。

试试这个:http://jsfiddle.net/maniator/VSQ4j/2/
setTimeout(testTime, $(this).index() * 150);

问题是对setTimeout的调用。你需要将一个函数传递给第一个参数,而不是调用一个函数。将调用更改为以下

setTimeout(testTime, $(this).index() * 150);