-1

I am trying to learn JS using a course on PluralSight, and I found this example which prints "hello world" every second, and stops after 5 seconds. This is the intended solution, and it works.

let counter = 0;
const intervalId = setInterval(() => {
  console.log('Hello World');
  counter += 1;

  if (counter === 5) {
    console.log('Done');
    clearInterval(intervalId);
  }
}, 1000);

I am trying to get it to use a callback instead of an inline function, but I am not able to capture intervalID. I tried passing 'this' as function argument, but that also doesn't work. What is the correct way here?

// doesn't work
let counter = 0;
const f = (intervalID) => {
    console.log("Hello World");
    counter += 1
    console.log(intervalID)
    if (counter ==5){
        console.log("Done")
        clearInterval(intervalID)
    }

}

const intervalID = setInterval(f, 1000)
  • Remove the `intervalID` parameter. The first parameter to `setInterval` is `A function to be executed every delay milliseconds. The function is not passed any parameters, and no return value is expected.` – CertainPerformance Jan 03 '19 at 01:18

1 Answers1

0

Your intervalID is not an argument passed to f, but if you just remove the argument it will work because the intervalID is lexically scoped so that it's available inside f.

let counter = 0;
const f = () => {
    console.log("Hello World");
    counter += 1
    console.log(intervalID)
    if (counter ==5){
        console.log("Done")
        clearInterval(intervalID)
    }

}

const intervalID = setInterval(f, 1000)

OR passing in the intervalID is also fine:

let counter = 0;
const f = (intervalID) => {
    console.log("Hello World");
    counter += 1
    console.log(intervalID)
    if (counter ==5){
        console.log("Done")
        clearInterval(intervalID)
    }

}

const intervalID = setInterval(() => f(intervalID), 1000)
Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100
  • Thanks a lot, the lexical scoping in JavaScript is really different. I don't even understand how is that possible! Can you explain a little bit more about it? – Harshdeep Gupta Jan 03 '19 at 01:40