Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is calling setTimeout with a negative delay ok?

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?

like image 952
ripper234 Avatar asked Dec 08 '11 12:12

ripper234


People also ask

What happens when if setTimeout () call with 0ms?

To explain: If you call setTimeout() with a time of 0 ms, the function you specify is not invoked right away. Instead, it is placed on a queue to be invoked “as soon as possible” after any currently pending event handlers finish running.

Does setTimeout affect performance?

No significant effect at all, setTimeout runs in an event loop, it doesn't block or harm execution.

Does setTimeout work asynchronous?

Working with asynchronous functionssetTimeout() is an asynchronous function, meaning that the timer function will not pause execution of other functions in the functions stack.

Is setTimeout a blocking call?

Explanation: setTimeout() is non-blocking which means it will run when the statements outside of it have executed and then after one second it will execute.


1 Answers

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.

like image 167
Jonathon Bolster Avatar answered Sep 22 '22 21:09

Jonathon Bolster