JavaScript: get code to run every minute

JavascriptJqueryHtml

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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);

Solution 2 - Javascript

You could use setInterval for this.

<script type="text/javascript">
function myFunction () {
    console.log('Executed!');
}

var interval = setInterval(function () { myFunction(); }, 60000);
</script>

Disable the timer by setting clearInterval(interval).

See this Fiddle: http://jsfiddle.net/p6NJt/2/

Solution 3 - Javascript

to call a function on exactly the start of every minute

let date = new Date();
let sec = date.getSeconds();
setTimeout(()=>{
  setInterval(()=>{
    // do something
  }, 60 * 1000);
}, (60 - sec) * 1000);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBluefireView Question on Stackoverflow
Solution 1 - JavascriptAndreas LouvView Answer on Stackoverflow
Solution 2 - JavascriptKnelisView Answer on Stackoverflow
Solution 3 - JavascriptWeiloryView Answer on Stackoverflow