具有自执行功能的 setInterval [英] setInterval with self-executing function

查看:55
本文介绍了具有自执行功能的 setInterval的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想第一次立即运行我的函数(没有超时),所以我这样做:

I want to run my function at the first time immediately (without timeout) so I do this:

setInterval(function(){
    alert("Boo");
}(), 1000);

该函数第一次执行,但在接下来的时间间隔内,什么也没发生.为什么?

The function executed at first time but in next intervals, nothing happened. Why?

推荐答案

更好的问题是,你实际上想要达到什么目的?

The better question is, what are you actually trying to achieve ?

你不会从自调用函数return任何东西,所以它会隐式返回undefined值,它被传递给setTimeout代码>.初始调用后,该行看起来像

You don't return anything from the self-invoking function, so it will return the undefined value implicitly, which is passed over to setTimeout. After the initial call, the line would look like

setInterval(undefined, 1000); 

这显然没有意义,也不会继续调用任何东西.

which obviously, makes no sense and won't continue calling anything.

您要么需要从自调用函数中return另一个函数,要么只是不使用自调用函数而只传递函数引用.

You either need to to return another function from your self-invoking function, or just don't use a self-invoking function and just pass over the function reference.

更新:

您更新了您的问题.如果您想在 init 上一次"运行一个函数,然后在该时间间隔内使用它,您可以执行类似

You updated your question. If you want to run a function "once" on init and after that use it for the interval, you could do something like

setInterval((function() {
    function loop() {
        alert('Boo');
    };

    loop();
    return loop;
}()), 1000);

这篇关于具有自执行功能的 setInterval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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