So from what I have understood, setInterval() is used to call a function on repeat on regular intervals. So basically it is a loop that executes a function forever periodically.
I am confused as to if I had to stop this execution at one point what would be the way to do it
for eg I am trying to print the message "hey" 3 times after 1 second each, but somehow it is printing it 3 times every second and is going on forever. What can I do to stop it after a set number of times.
This is the code that I've been trying
var i = 3;
function message() {
console.log("hey");
}
while(i > 0) {
setInterval(message, 1000);
i = i - 1;
}
setInterval
is not intended to ranx
times, but rather to run everyx
ms. If you want it to runx
times, see @eis 's answer how it can be accomplished usingsetTimeout
instead.