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?

Answers:

Answer

You can also do it with

setTimeout(function() {ajaxUpdate(10)}, 1000);
Answer
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:

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

Answer

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

You can use this JavaScript Timer class.

Answer

You can use too jQuery Timers: http://plugins.jquery.com/project/timers

Answer

You can use the function setTimeout(String fonc, Integer delay). For example, to execute your code each second you can do :

window.setTimout("ajaxUpate",100);

Hope i answer to your question ;)

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.