Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - jQuery interval

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.

like image 829
Alfred Avatar asked Sep 25 '11 15:09

Alfred


People also ask

How do you create an interval in JavaScript?

JavaScript interval to be set use setInterval() function. It could be defined simply as a method which allows you to invoke functions in set intervals. The JS setInterval() function is similar to the setTimeout method.

Is setInterval jQuery?

setInterval is not a jQuery function. It is a builtin JavaScript function.

What is interval in JS?

In JavaScript, a block of code can be executed in specified time intervals. These time intervals are called timing events. There are two methods for executing code at specific intervals. They are: setInterval()


1 Answers

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

$(function() {
    sayHi();

    function sayHi() {
       setTimeout(sayHi,30000);
       alert('hi');
    }
});
like image 62
tvanfosson Avatar answered Oct 16 '22 01:10

tvanfosson