简体   繁体   中英

IIFE and Arrow Functions with setInterval plain JS

I have the following code:

 window.setInterval((array => { console.log(array[0]++); console.log(array[1]++); })([0, 0]), 500);

I expected that the code above would yield 0 and 0 each run (500ms). However, it doesn't. It only ran once. When I tried:

 window.setInterval((array => () => { console.log(array[0]++); console.log(array[1]++); })([0, 0]), 500);

It worked. I thought that the first one will still print out 0 and 0 every 500ms as the IIFE with parameter array will always be given the values [0, 0] per run (however, this wasn't the case, it ran only once!). Then, the second code somehow allows array to "remember" its previous value and update its value per run. Could someone please explain this to me?

The first parameter passed to setInterval should be a function. In the first snippet, you're invoking a function immediately and returning undefined :

window.setInterval((array => {
  console.log(array[0]++);
  console.log(array[1]++);
})([0, 0]), 500);

is equivalent to

window.setInterval(() => {
  // do something, return undefined
})(), 500);

and once the IIFE is evaluated:

window.setInterval(undefined, 500);

So, you need something like your second snippet, in which the IIFE also returns a function:

 window.setInterval((array => () => { console.log(array[0]++); console.log(array[1]++); })([0, 0]), 500);

Though, you might consider defining array inside the outer IIFE to make the code a bit clearer:

 window.setInterval( (() => { const array = [0, 0]; return () => { console.log(array[0]++); console.log(array[1]++); }; })(), 500 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM