SetTimeout doesn't work with average negative numbers
If you call setTimeout
with a small or large negative number, the callback is triggered immediately, but with an average negative number, the callback is never triggered. Can someone explain this?
// Y and Z are printed, but not X
var x = -7677576503;
var y = -1000000000;
var z = -10000000000;
setTimeout(function () {
console.log('x');
}, x);
setTimeout(function () {
console.log('y');
}, y);
setTimeout(function () {
console.log('z');
}, z);
(tested on Chromium 57.0.2987.98 and Firefox 50.1.0)
source to share
I think I have an answer.
according to MDN :
Browsers including Internet Explorer, Chrome, Safari, and Firefox store latency as a 32-bit signed integer.
the browser will convert this value to a 32-bit signed int. so when it sees the values ββyou pass, we can assume that it actually acts on the ones it converts to that type, and the ECMAScript spec says return values ββfrom bitwise operations must be 32-bit int.
Runtime Semantics: Evaluation Production A: A @B, where @ is one of the bitwise operators in the above products, is evaluated like this:
... [snipped].
Return the result of applying the bitwise @ operator in lnum and rnum. The result is a signed 32-bit integer.
so if we match this and check the values ββyou provided:
x | 0 === 912358089
so the timeout will eventually be executed .. only after a while. y | 0 === -1000000000
and the callback is immediately triggered *. z | 0 === -1410065408
, still negative, yet fired at once *.
* all tests performed in chrome latest stable
you can check this with other negatives that will have a positive effect when converted to a 32-bit signed int. -7000000000 | 0
would result in a call 1589934592 and the call setTimeout(fn, -7000000000)
doesn't seem to fire ... today.
with that in mind this is my best guess as to what's going on. good luck!
edit: thanks to Vivek Athalye , I think I have confirmation, this is what's going on.
-4294967290000 | 0 === 6000
and if you run setTimeout(_ => console.log(1), -4294967290000)
that runs in aprox. 6 seconds.
source to share