-1

I was looking into how Node JS executes code. If I set the 'sleep' parameter to 1 in both functions it works as expected.
But with different delays in the two functions, it skips iterations for the function with the longest delay.
I would expect function b to log all numbers from 0 to 99 but slower than function a.

See the code in mycompiler.io

a()
b()

async function a() {
  for (n=1; n<100; n++) {
    console.log('a', n)
    await sleep(1)
  }
}

async function b() {
  for (n=1; n<100; n++) {
    console.log('b', n)
    await sleep(3)
  }
}

function sleep(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  })
} 
René
  • 3
  • 2

1 Answers1

1

As @CertainPerformance mentioned in the comment you must declare your variable if you want your for loops to perform correctly here. for(let n=1; n<100; n++)

Sine you're not running node in strict mode, those n variables are now essentially referencing a single shared variable, so you should notice, there are actually no numbers getting skipped, rather both functions are creating a single shared iteration from 1 to 99.

Here's what a working version of this looks like:

'use strict'

a()
b()

async function a() {
  for (let n=1; n<100; n++) {
    console.log('a', n)
    await sleep(1)
  }
}

async function b() {
  for (let n=1; n<100; n++) {
    console.log('b', n)
    await sleep(3)
  }
}

function sleep(ms) {
  return new Promise((resolve) => {
    setTimeout(resolve, ms);
  })
} 

To echo again what was said in the comments, had you run your script in strict mode this error would have been thrown when you ran the code:

ReferenceError: n is not defined
Eric Uldall
  • 2,282
  • 1
  • 17
  • 30