JavaScript - jQuery interval

ぃ、小莉子 提交于 2019-11-27 05:58:32

问题


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

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

I want to alert hi when 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?

You can see my fiddle here.


回答1:


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

$(function() {
    sayHi();

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



回答2:


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

$(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();
});



回答3:


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.

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



回答4:


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

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

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



回答5:


$(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 setTimeout not setInterval.



来源:https://stackoverflow.com/questions/7546565/javascript-jquery-interval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!