JavaScript - jQuery间隔

bla*_*d Ψ 10 javascript jquery setinterval

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

$(document).ready( function() {
    alert("hi");
setInterval(function() {
    alert("hi");
}, 30000);
});
Run Code Online (Sandbox Code Playgroud)

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

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

tva*_*son 18

您可以使用setTimeout,并让回调重新安排自己.

$(function() {
    sayHi();

    function sayHi() {
       setTimeout(sayHi,30000);
       alert('hi');
    }
});
Run Code Online (Sandbox Code Playgroud)


Rob*_*b W 9

将代码包装在函数中.然后,将函数作为第一个参数传递给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();
});
Run Code Online (Sandbox Code Playgroud)