JavaScript - jQuery interval

Alfred picture Alfred · Sep 25, 2011 · Viewed 87.7k times · Source

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.

Answer

tvanfosson picture tvanfosson · Sep 25, 2011

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

$(function() {
    sayHi();

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