/ 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);
                // 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);
                            
                                Expand |
                                Embed | Plain Text
                            
                        
                        Copy this code and paste it in your HTML
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);
};
Comments
 Subscribe to comments
                    Subscribe to comments
                
                