How to implement pauses in a countdown loop?

Viewed 25

//This function is to implement sleep in js
function sleep(milliseconds) {
  const date = Date.now();
  let currentDate = null;
  do {
    currentDate = Date.now();
  } while (currentDate - date < milliseconds);
}

for (let i = 10; i != 0; i--) {
  document.getElementById("timerLabel").innerHTML = i;
    sleep(1000);
  }
<label id="timerLabel"></label>

1 Answers

This is an alternative way of doing the countdown: a simple setInterval() will be quite enough:

function countdown(n){
 const el=document.getElementById("timerLabel"),
  intv=setInterval(()=>(el.textContent=--n)||clearInterval(intv), 1000);
 el.textContent=n;
}
 
countdown(10);
<label id="timerLabel"></label>

Related