RunJS icon indicating copy to clipboard operation
RunJS copied to clipboard

Question about logged result

Open benjaminmodayil opened this issue 3 years ago • 4 comments

I was trying to run a code exercise from this week's Bytes newsletter and saw a weird result.

const arr = [7, 1, 4, 3, 2];

for (const elem of arr) {
  setTimeout(() => console.log(elem), elem);
}
CleanShot 2022-08-08 at 16 19 57@2x

I assume the 5 is related to the amount of items in the array, but why is that logging? If I comment out the for loop it doesn't log.

benjaminmodayil avatar Aug 08 '22 20:08 benjaminmodayil

The 5 you're seeing is the ID that gets returned from setTimeout.

lukehaas avatar Aug 09 '22 07:08 lukehaas

Whoops. Forgot setTimout returns that… 🤦‍♂️

On Tue, Aug 9, 2022 at 3:54 AM Luke Haas @.***> wrote:

The 5 you're seeing is the ID that gets returned from setTimeout.

— Reply to this email directly, view it on GitHub https://github.com/lukehaas/RunJS/issues/463#issuecomment-1209039446, or unsubscribe https://github.com/notifications/unsubscribe-auth/AC54TIS5XCSRZFBXQP35JS3VYIFCPANCNFSM556MH25A . You are receiving this because you authored the thread.Message ID: @.***>

benjaminmodayil avatar Aug 09 '22 09:08 benjaminmodayil

Is it?

const arr = [7, 1, 4, 3, 2];

for (const elem of arr) {
  console.log('Queing element', { elem });
  setTimeout(() => console.log(elem), elem);
}

Returns an extra 10. Why would it change?

[7, 1, 4, 3, 2].forEach(x => setTimeout(() => console.log(x), x))

Doesn't return a 5.

btecu avatar Aug 09 '22 12:08 btecu

@btecu the ID that gets returned by setTimeout won't always be the same.

lukehaas avatar Aug 09 '22 12:08 lukehaas