SetInterval with infinity

So if I do:

setInterval(function(){ console.log("1"); },Infinity); 

It keeps logging 1 as if it is for loop . Why is this behavior?

+5
source share
3 answers

When a float / number Infinity needs to be converted to a 32-bit integer value in JavaScript, as for setTimeout, it is 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 converts argument to one of 2 32 integer values ​​in the range -2 31 through 2 31 -1 inclusive. This thesis has the following features:

  • Let the number be ToNumber(argument) .
  • ReturnIfAbrupt(number) .
  • If the number is NaN, +0, -0, + ∞ or -∞, return +0.
  • [...]
+7
source

Infinity used only in arithmetic, and therefore its behavior is determined only in arithmetic. In any other context, it is simply 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}.

Since this object is not used as the delay setTimeout parameter, this function is executed as if the object had not been sent, therefore 0 .

+3
source

My closest assumption is that the argument of the interval you specify in setInterval is divided by time counters to determine if the next iteration should be performed. The function must be called without an interval, since it is zero when any number is divisible by infinity.

 if (counter / Infinity === 0) callback(); 

In the above code, callback() will execute for any counter.

+1
source

Source: https://habr.com/ru/post/1238607/


All Articles