Posted By

McSodbrenner on 02/15/13


Tagged

javascript


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

Abiotic
jbyerson


Exact Javascript Timeout


 / Published in: JavaScript
 

This is a more precise version of the native setTimeout(). It uses the same parameters as setTimeout, but adds a third parameter "resolution" which defines how often (in ms) to check for the time that passed.

// alert after 5 seconds with an inaccuracy of 20 milliseconds
var timeout = setExactTimeout(function(){
   alert('done');
}, 5000, 20);

// comment out to show "done"
clearExactTimeout(timeout);
  1. var setExactTimeout = function(callback, duration, resolution) {
  2. var start = (new Date()).getTime();
  3. var timeout = setInterval(function(){
  4. if ((new Date()).getTime() - start > duration) {
  5. callback();
  6. clearInterval(timeout);
  7. }
  8. }, resolution);
  9.  
  10. return timeout;
  11. };
  12.  
  13. var clearExactTimeout = function(timeout) {
  14. clearInterval(timeout);
  15. };

Report this snippet  

You need to login to post a comment.