Skip to content

Instantly share code, notes, and snippets.

@McSodbrenner
Last active September 29, 2021 18:51
Show Gist options
  • Select an option

  • Save McSodbrenner/6129351 to your computer and use it in GitHub Desktop.

Select an option

Save McSodbrenner/6129351 to your computer and use it in GitHub Desktop.
Javascript: Exact Javascript Timeout

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);
var setExactTimeout = function(callback, duration, resolution) {
var start = (new Date()).getTime();
var timeout = setInterval(function(){
if ((new Date()).getTime() - start > duration) {
callback();
clearInterval(timeout);
}
}, resolution);
return timeout;
};
var clearExactTimeout = function(timeout) {
clearInterval(timeout);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment