Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set a timer in javascript

I want to run the following code:

ajaxUpdate(10);

With a delay of 1 second between each iteration. How can I do this?

like image 938
Ali Avatar asked Jan 20 '09 08:01

Ali


People also ask

Is there a timer in JavaScript?

JavaScript offers two timer functions setInterval() and setTimeout(), which helps to delay in execution of code and also allows to perform one or more operations repeatedly.

How do you wait for 5 seconds in JavaScript?

The standard way of creating a delay in JavaScript is to use its setTimeout method. For example: console.log("Hello"); setTimeout(() => { console.log("World!"); }, 5000); This would log “Hello” to the console, then make JavaScript wait 5 seconds, then log “World!”


3 Answers

var i = window.setInterval( function(){ 
          ajaxUpdate(10); 
 }, 1000 ); 

This will call ajaxUpdate every second, until such a time it is stopped.

And if you wish to stop it later:

window.clearInterval( i ); 

If you wish to only run it once however,

var i = window.setTimeout( function(){ 
          ajaxUpdate(10); 
 }, 1000 ); 

Will do the trick, and if you want to stop it running before it gets around to running once

window.clearTimeout(i); 

The "window" prefix is not strictly nessecary, but its a good idea, because you never know when somebody else might like to create something else with the same name in visible scope that behaves differently.

For a complete reference on this, I always find MDC Very Helpful:

  • MDC: window.setInterval
  • MDC: window.clearInterval
  • MDC: window.setTimeout
  • MDC: window.clearTimeout

Also, you may wish to read this article on timers by John Resig,

  • ejohn.org : How Javascript Timers work
like image 64
Kent Fredric Avatar answered Sep 28 '22 09:09

Kent Fredric


You can also do it with

setTimeout(function() {ajaxUpdate(10)}, 1000);
like image 30
Raibaz Avatar answered Sep 28 '22 08:09

Raibaz


You can use setInterval() for that. Create an anonymous function to be called, and use the time in milliseconds:

var myInterval = window.setInterval(function() { ajaxUpdate(10); }, 1000);
like image 31
Greg Avatar answered Sep 28 '22 07:09

Greg