Javascript clearInterval() deducts another 1 second when trying to pause

Viewed 32

I have built a recorder with timer of 15 seconds which works fine on start and stop. But when we pause the recording, the recording pauses but the timer deducts another 1 second before stopping.

Following is the js code where I am doing this stuff of getting the recorder state and doing clearInterval(countDown) in it.

p.s I have also tried putting timeSecond inside else

    const countDown = setInterval(() => {

  displayTime(timeSecond);
  if (timeSecond == 0 || timeSecond < 1) {
    endCount();
    clearInterval(countDown);
  }  
  if (recorder && recorder.state === 'paused') {
  
  clearInterval(countDown)
}
  else{
  timeSecond--;
  }
}, 1000);

const countDown = setInterval(() => {

  displayTime(timeSecond);
  if (timeSecond == 0 || timeSecond < 1) {
    endCount();
    clearInterval(countDown);
  }  
  if (recorder && recorder.state === 'paused') {
  
  clearInterval(countDown)
}
  timeSecond--;
}, 1000);

1 Answers

You need to execute the function.

setInterval will start one unit after it is called

And you need to leave the function if you do not want it to fall through to the timeSecond--;

const output = document.getElementById("time");
const displayTime = time => output.textContent = time;
const endCount = () => output.textContent = "done";
let timeSecond = 5;
let tId;
const recorder = { state: "" }
const countDown = ()=> {
  displayTime(timeSecond);
  if (timeSecond < 1) {
    endCount();
    clearInterval(tId);
    return;
  }
  if (recorder && recorder.state === 'paused') {
    clearInterval(tId);
    return;
  }
  timeSecond--;
};  
countDown()
tId = setInterval(countDown,1000);
<span id="time">Hello</span>

Related