RunJS
RunJS copied to clipboard
Question about logged result
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);
}
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.
The 5 you're seeing is the ID that gets returned from setTimeout.
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: @.***>
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 the ID that gets returned by setTimeout won't always be the same.