So If i am doing:
setInterval(function(){
console.log("1");
},Infinity);
It keeps on logging 1
as if it is a for loop
. Why is that behaviour?
So If i am doing:
setInterval(function(){
console.log("1");
},Infinity);
It keeps on logging 1
as if it is a for loop
. Why is that behaviour?
-
2
1) Because
setInterval
essentially is afor
loop. 2) Because the parison to determine whether it's time for the next iteration likely arrives at the answer yes at any time using a parison toInfinity
. – Since this code is rather nonsensical, I wouldn't expect any particular "right" answer here anyway. – deceze ♦ Commented Dec 18, 2015 at 8:03 - @deceze What I think is the output is nonsensical. – void Commented Dec 18, 2015 at 8:07
- 1 Garbage in, garbage out. :) – deceze ♦ Commented Dec 18, 2015 at 8:11
- @deceze hehe yeah, right! – void Commented Dec 18, 2015 at 8:11
3 Answers
Reset to default 11When the float/number Infinity
needs to be converted to a 32-bit integer value in JavaScript, as it does for setTimeout, it's converted to zero:
console.log(typeof Infinity); // number
console.log(Infinity | 0); // 0
ECMA-262 6e Section 7.1.5
ToInt32 ( argument )
The abstract operation
ToInt32
convertsargument
to one of 232 integer values in the range −231 through 231−1, inclusive. This abstract operation functions as follows:
- Let number be
ToNumber(argument)
.ReturnIfAbrupt(number)
.- If number is NaN, +0, −0, +∞, or −∞, return +0.
- [...]
Infinity
only has use in arithmetics, and its behaviour is therefore only defined in arithmetics. In any other context it's just an object with some properties:
The value of Infinity is +∞ (see 6.1.6). This property has the attributes { [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]: false }.
As this object has no use as the delay
parameter of setTimeout
that function executes as if no object was supplied, so 0
.
My closest guess is that the interval argument you specify in setInterval
is subjected to division when pared with the time counters to determine if the next iteration should be done. The function must be called without an interval since it is zero when any number is divided by Infinity.
if (counter / Infinity === 0)
callback();
In the above code, callback()
will execute for any counter.