JavaScript - jQuery interval

允我心安 提交于 2019-11-28 11:08:58

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.

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