Timeout a function in Javascript

published Apr 05, 2019 02:50   by admin ( last modified Apr 05, 2019 02:50 )

Here's one way that seems to work, you set a time to change a function-scoped variable and return out of the function when that changes.

function thisShouldTimeOut() {

  var shouldIStopDoingThis = false

  setTimeout(() => {
    shouldIStopDoingThis = true
  }, 2000)

  for () { // some loopy stuff
    if (shouldIStopDoingThis) {
      return
    }
  }
}