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 - (new Date().getTime() - currentTimeMillis);
Given that sleepTime can be a negative number, is it safe to call setTimeout, like this:
setTimeout(callback, sleepTime)
Or do I need to check for negative values before calling setTimeout?
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/ ):
I haven’t tested this myself, but like Thomasz said, it’s probably better to be safe.