setInterval and clearInterval

var intervalId;
var runCount = 1;

function sayHello() {
if (runCount > 5) {
clearInterval(intervalId)
}
console.log(runCount, “Hello!”);
runCount++;

}
console.log(“And the wait starts…”);
intervalId = setInterval(sayHello, 1000);

why the above code printing hello 6 times?

Hi @akashagarwal1321,
This code prints hello 6th time because of the console.log(runCount,“Hello!”) after the if block. After executing the if block it will execute the console line written in 8th line of code according to the below image to complete the execution of the code.

1 Like

Okay Does it mean that clearInterval() just only stops the next setInterval() call and does not act like break?

Yes we can say that. to read more about setInterval() function you can refer to the provided link.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.