Is calling setTimeout with a negative delay ok?

According to the MDN reference, the specification requires that there is a minimum timeout.

If you provide something less than this (HTML5 spec says 4ms) then the browser will just ignore your delay and use the minimum.

So negatives should be fine, since it'll just be less than the minimum.


Apparently, this isn't always the case (isn't that always the way with web development!). According to ( http://programming.aiham.net/tag/browser-compatibility/ ):

Providing setTimeout a negative time will not always result in the callback function being called. This works in other browsers, but in Internet Explorer (8 or lower) you have to make sure any negative times are changed to zero.

I haven't tested this myself, but like Thomasz said, it's probably better to be safe.


You could also use a conditional statement, like so:

if (sleepTime < 0) {
  sleepTime = 0;
}
setTimeout(callback, sleepTime);

Better be safe than sorry:

setTimeout(callback, Math.max(sleepTime, 0))