最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - setInterval with Infinity - Stack Overflow

programmeradmin2浏览0评论

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?

Share Improve this question asked Dec 18, 2015 at 8:00 voidvoid 36.7k10 gold badges69 silver badges111 bronze badges 4
  • 2 1) Because setInterval essentially is a for 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 to Infinity. – 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
Add a ment  | 

3 Answers 3

Reset to default 11

When 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 converts argument to one of 232 integer values in the range −231 through 231−1, inclusive. This abstract operation functions as follows:

  1. Let number be ToNumber(argument).
  2. ReturnIfAbrupt(number).
  3. If number is NaN, +0, −0, +∞, or −∞, return +0.
  4. [...]

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.

发布评论

评论列表(0)

  1. 暂无评论