Is calling setTimeout with a negative delay ok?

前端 未结 4 999
后悔当初
后悔当初 2021-02-06 20:44

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          


        
4条回答
  •  别那么骄傲
    2021-02-06 21:30

    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)
    

提交回复
热议问题