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)