How to stop setInterval and resume?

Asked by At

How can I stop setInterval and then resume from the same place?

Example:

start ---> 1,2,3,4,5 .... ---> stop ---> start ---> 6,7,8 ...

index.html

<div onclick=start()>start</div>  
<div onclick=stop()>stop</div>

index.js

let refreshInterval = null;

start() {
  var i = 0;
    refreshInterval = setInterval(function() {
      console.log(i);
      i++;
    }, 1000);
}


stop() {
    ???????
}

2 Answers

5
Nina Scholz On Best Solutions

You need a global variable i and for stopping a clearInterval.

function start() {
    if (refreshInterval !== undefined) return; // prevent more than one interval
    refreshInterval = setInterval(function() {
        console.log(i);
        i++;
    }, 1000);
}

function stop() {
    clearInterval(refreshInterval);
    refreshInterval = undefined;
}

var refreshInterval,
    i = 0;
<div onclick="start()">start</div>
<div onclick="stop()">stop</div> 

1
Code Maniac On

You can keep the count variable in outer scope so it will not reset everytime you run start function

let refreshInterval = null;
let count = 0

function start() {
    refreshInterval = setInterval(function() {
      document.getElementById('value').innerText = count
      count++;
    }, 1000);
    document.getElementById('start').disabled=true
}


function stop() {
    clearInterval(refreshInterval)
    document.getElementById('start').disabled=false
}
#counter{
  padding: 0.25rem;
  font-size: 1.25rem;
  border: 1px solid black;
  margin-bottom: 1rem;
}
<div  id='counter'><span>counter:</span>
<span id='value'/>0</div>
<button onclick=start() id='start'>start</button>
<button onclick=stop() id='stop'>stop</button>