#stackoverlog#javascript#es6

Stop setInterval function in JavaScript

Creating a can-stop setStoppableInterval function

const setStoppableInterval = (
  handler,
  intervalTimeout,
  stopCondition,
) => {
  let interval

  interval = setInterval(() => {
    handler()
    if (stopCondition()) {
      clearInterval(interval)
    }
  }, intervalTimeout)
}

Using the setStoppableInterval function

setStoppableInterval(
  () => {
    // do something here
  },
  100,
  () => {
    // condition here, return a boolean value
    const stop = isStop()

    return stop
  },
)    
An Tran

An Tran

A passionate web developer, self-learner and music lover.

Read More