如何立即启动setInterval循环? [英] How to start setInterval loop immediately?

查看:110
本文介绍了如何立即启动setInterval循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个简单的 setInterval

setInterval(function() {
      // Do something every 9 seconds
}, 9000);

第一个动作将在9秒后发生( t = 9s )。如何强制循环立即执行第一个操作( t = 0 )?

The first action will happen after 9 seconds (t=9s). How to force the loop to perform the first action immediately (t=0)?

我认为它应该到期到 setInterval 的机制有延迟 - 动作 - 延迟 - 动作... 循环;而不是动作 - 延迟 - 动作 - 延迟... 循环。

I think it is due to the mechanism of setInterval to have Delay - Action - Delay - Action ... loop; instead of Action - Delay - Action - Delay ... loop.

编辑:我的函数确实是一个循环

My function is indeed a loop as

setInterval(function(){
$('.test').each(function(idx){
    var duration = 1000;
    $(this).delay(duration*idx);
    Some stuff here
});
}, 4000);


推荐答案

保持简单。您可以使用命名函数而不是匿名函数;调用它并设置它的间隔。

Keep it simple. You can use a named function instead of an anonymous function; call it and set an interval for it.

function doSomething() {
    console.log("tick");
}
doSomething();
setInterval(doSomething, 9000);

如有必要,请创建范围:

Create a scope if necessary:

(function() {
    function doSomething() {
        console.log("tick");
    }
    doSomething();
    setInterval(doSomething, 9000);
})();

最后,以下工作无需创建或影响 x

Finally, the following works without creating or affecting x:

setInterval(function x() {
    console.log("tick");
    return x;
}(), 9000);

这篇关于如何立即启动setInterval循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆