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.
Asked
Active
Viewed 1.7e+01k times
107

Bluefire
- 13,519
- 24
- 74
- 118
-
http://stackoverflow.com/questions/316278/timeout-jquery-effects – maialithar Nov 09 '12 at 08:22
-
setInterval(expression, timeout); runs the code/function in intervals, with the length of the timeout between them. – Jai Nov 09 '12 at 08:24
-
Possible duplicate of [Calling a function every 60 seconds](https://stackoverflow.com/questions/3138756/calling-a-function-every-60-seconds) – Heretic Monkey Jan 22 '18 at 22:28
3 Answers
184
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);

Michal
- 459
- 2
- 7
- 25

Andreas Louv
- 46,145
- 13
- 104
- 123
-
5+1 for `60 * 1000`, but it's also a good idea to define the function outside rather than passing an anonymous function. – Adi Nov 09 '12 at 08:24
-
1Question, though: if I put that, will the code be executed on the loading of the page, or will it happen 60 seconds after the loading? – Bluefire Nov 09 '12 at 08:28
-
2
16
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/

Knelis
- 6,782
- 2
- 34
- 54
4
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);

Weilory
- 2,621
- 19
- 35
-
2If it's important to continue executing at the start of every minute for any moderate length of time, it's worth noting that JS's `setInterval` is not very reliable at exact time keeping, and this will likely drift further away from the start of the minute the longer it runs. – DBS Feb 07 '22 at 13:38