开发者

JavaScript - jQuery interval

开发者 https://www.devze.com 2023-04-08 19:55 出处:网络
I am using JavaScript with jQuery. I have the following script to alert hi every 30 seconds. $(document).ready( function() {

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开发者_C百科 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.


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

$(function() {
    sayHi();

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


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


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);


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

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

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


$(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.

0

精彩评论

暂无评论...
验证码 换一张
取 消