JavaScript setInterval立即运行 [英] JavaScript setInterval immediately run

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

问题描述

我找到了一个在javascript中运行间隔的解决方案,而不是等待第一次超时

I found a solution to run interval in javascript immidiately, not waiting for a first "timeout"

setInterval(function hello() {
  console.log('world');
  return hello;
}(), 2500);

但问题是这个解决方案不起作用就像这样构造

But problem is this solution isn't working is construction like this

(function () {
    window.Banner = {

        doMagic: function () {
            setInterval(function magic() {
                console.log('magic');
                return magic;
            }, 2500);
        }
    }
})();

Banner.doMagic();

我试图返回Banner方法,命名并返回,但没有成功。
点是实际构造中的点要复杂得多,所以我不能将它重写为返回setTimeout解决方案,因为广泛提供,所以找到我做错了什么是非常完美的。

I've tried to return Banner method, to name it and return and no success. Point is what in real construction is much more complex, so i can't just rewrite it to "return setTimeout" solution, as offered widely, so it would be really perfect to find what am i doing wrong with this one.

http://jsfiddle.net/5jawxLnr/ 3 /

推荐答案

也许最合适的方法是在setInterval之外进行整个回调调用并将其放在一个单独的变量中:

Perhaps the most proper way to do it would be to take the whole callback outside of the setInterval call and put it in a separate variable:

(function () {
    window.Banner = {

        doMagic: function () {
            var magic = function() {
                console.log('magic');
            };
            setInterval(magic, 2500);
            magic();
        }
    }
})();

Banner.doMagic();

效果与您的第一个代码相同,但这样您的代码更清晰。

The effect is the same as your first code, but this way your code is a little cleaner.

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

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