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.5e+01k times
94
Bluefire
- 12,429
- 22
- 67
- 111
-
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
167
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
- 437
- 7
- 23
Andreas Louv
- 44,338
- 13
- 91
- 116
-
4+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
13
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,297
- 2
- 33
- 53
0
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
- 1,807
- 9
- 24
-
If 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