JavaScript - jQuery 间隔

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7546565/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:39:52  来源:igfitidea点击:

JavaScript - jQuery interval

javascriptjquerysetinterval

提问by blasteralfred Ψ

I am using JavaScript with jQuery. I have the following script to alert hievery 30 seconds.

我在 jQuery 中使用 JavaScript。我有以下脚本hi每 30 秒发出一次警报。

$(document).ready( function() {
    alert("hi");
setInterval(function() {
    alert("hi");
}, 30000);
});

I want to alert hiwhen the page loads (when document / page gets completely loaded) and on every 30 seconds interval afterwards (like hi(0s) - hi(30s) - hi(60s).. etc). But my solution works on two instances. One on DOM ready and the other in a loop. Is there any way to do the same in a single instance?

我想hi在页面加载时(当文档/页面完全加载时)以及之后每 30 秒间隔(如hi(0s) - hi(30s) - hi(60s) 等)发出警报。但我的解决方案适用于两个实例。一个在 DOM 上准备好,另一个在循环中。有没有办法在单个实例中做同样的事情?

You can see my fiddle here.

你可以在这里看到我的小提琴。

回答by tvanfosson

You could use setTimeout instead and have the callback reschedule itself.

您可以改用 setTimeout 并重新安排回调本身。

$(function() {
    sayHi();

    function sayHi() {
       setTimeout(sayHi,30000);
       alert('hi');
    }
});

回答by Rob W

Wrap your code in a function. Then, pass the function as a first argument to setInterval, and call the function:

将您的代码包装在一个函数中。然后,将该函数作为第一个参数传递给setInterval,并调用该函数:

$(document).ready( function() {
    //Definition of the function (non-global, because of the previous line)
    function hi(){
        alert("hi");
    }

    //set an interval
    setInterval(hi, 30000);

    //Call the function
    hi();
});

回答by Ondrej Simek

Well, there probably is a way of doing it in just one call..

好吧,可能有一种方法可以在一次通话中做到这一点。

setInterval(
    (function x() {
        alert('hi');
        return x;
    })(), 30000);

Another solution would be to use arguments.callee, but as it is now deprecated, it is generally not recommended to use it.

另一种解决方案是使用arguments.callee,但由于它现在已被弃用,因此通常不建议使用它。

setInterval(
    (function() {
        alert('hi');
        return arguments.callee;
    })(), 30000);

回答by Darin Dimitrov

No, that's not possible with setInterval. You could use setTimeout for example:

不,这是不可能的setInterval。您可以使用 setTimeout 例如:

function foo() {
    alert('hi');
    setTimeout(foo, 30000);
}

$(function() {
    foo();
});

回答by daryl

$(function() {

    function heythere() {
        alert('hi');
        setTimeout(heythere,30000);
    }

    heythere();

});

If you want it to only run once after 30 seconds, you are looking to use setTimeoutnot setInterval.

如果您希望它在 30 秒后仅运行一次,则您希望使用setTimeoutnot setInterval