Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: get code to run every minute

Is there a way to make some JS code be executed every 60 seconds? I'm thinking it might be possible with a while loop, but is there a neater solution? JQuery welcome, as always.

like image 407
Bluefire Avatar asked Nov 09 '12 08:11

Bluefire


People also ask

How do you repeat a code in JavaScript?

repeat() is an inbuilt function in JavaScript which is used to build a new string containing a specified number of copies of the string on which this function has been called. Syntax: string. repeat(count);

How do I make code run every second?

Use setInterval() to run a piece of code every x milliseconds. You can wrap the code you want to run every second in a function called runFunction . Save this answer.

Does JavaScript run automatically?

Within a browser, JavaScript doesn't do anything by itself. You run JavaScript from inside your HTML webpages. To call JavaScript code from within HTML, you need the <script> element.


1 Answers

Using setInterval:

setInterval(function() {     // your code goes here... }, 60 * 1000); // 60 * 1000 milsec 

The function returns an id you can clear your interval with clearInterval:

var timerID = setInterval(function() {     // your code goes here... }, 60 * 1000);   clearInterval(timerID); // The setInterval it cleared and doesn't run anymore. 

A "sister" function is setTimeout/clearTimeout look them up.


If you want to run a function on page init and then 60 seconds after, 120 sec after, ...:

function fn60sec() {     // runs every 60 sec and runs on init. } fn60sec(); setInterval(fn60sec, 60*1000); 
like image 67
Andreas Louv Avatar answered Nov 09 '22 01:11

Andreas Louv