The following snippet sets a timeout that I\'d like to last at least a second:
var currentTimeMillis = new Date().getTime();
// do stuff...
var sleepTime = 1000
Hmm... The solutions mentioned solves the problem at the call to setTimeout
, so it needs to be written each time a call is made. Isn't it better to solve it directly in setTimeout
?
// Run this once.
(function(){
var oldSetTimeout = setTimeout
setTimeout = function(callback, delay){
return oldSetTimeout(callback, Math.max(delay, 0))
}
})()
// Call setTimeout safely with a negative delay.
setTimeout(function(){ console.log("Hello World") }, -42)