setInterval()

setInterval() is a function that repeatedly executes a specified function or code block at a defined interval in milliseconds. It's often used for tasks like creating animations, polling for updates, or running periodic checks. The function specified will keep executing at the defined interval until you explicitly stop it using clearInterval().

basic interval


let count = 0;
let max = window.prompt("Count up to what #?");
max = Number(max);

const timer1 = setInterval(countUp, 1000); //function is passed as argument

function countUp() {
  count += 1;
  console.log(count);
  if (count >= max) {
    clearInterval(timer1);
  }
}

      

page


inputUser = document.getElementById("inputUser");
buttonSubmit = document.getElementById("buttonSubmit");
p1 = document.getElementById("p1");

let count = 0;
let max = 0;
let timer1;

buttonSubmit.onclick = function () {
  max = Number(inputUser.value);
  timer1 = setInterval(countUp, 1000); //function is passed as argument
};

function countUp() {
  count += 1;
  p1.innerHTML += `
${count}`; if (count >= max) { clearInterval(timer1); } }