Creating Time Delays


/ Published in: JavaScript
Save to your folder(s)

Source: Creating time delays @ howtocreate

There are two ways of creating time delays with JavaScript. The first is more simple and will simply wait for a specified amount of time before executing a function. The second does the same but will repeatedly execute the function.

Note, most browsers have a minimum delay length of between 25 and 75 ms. If a shorter delay is specified, the actual delay will be the minimum delay length. Even with higher numbers, the delay is never perfect. Most browsers will take slightly longer than the time you ask for, typically just a few miliseconds error. Some may correct their errors over time with interval timers. Also note, setting many timers with short delays on one page will cause the browser to become slow and somewhat unresponsive. Three or four timers is usually the reliable limit.


Copy this code and paste it in your HTML
  1. // -----------------------------
  2. // setTimeOut
  3.  
  4. window.setTimeout(referenceToFunction,timeInMilliseconds);
  5. window.setTimeout('runMoreCode()',timeInMilliseconds);
  6. window.setTimeout('runMoreCode(\''+someString+'\','+someNumber+')',10);
  7.  
  8. window.setTimeout(function (a,b) {
  9. //do something with a and b
  10. },10,someString,someObject);
  11.  
  12. // -----------------------------
  13. // setTimeInterval
  14.  
  15. window.setInterval(function (a,b) {
  16. //do something with a and b
  17. },10,someString,someObject);
  18.  
  19. // -----------------------------
  20. // Clearing timeouts and intervals
  21.  
  22.  
  23. var myInterval = window.setInterval(function (a,b) {
  24. myNumber++;
  25. },1000);
  26. window.setTimeout(function (a,b) {
  27. clearInterval(myInterval);
  28. },3500);

URL: http://www.howtocreate.co.uk/tutorials/javascript/timers

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.