Discover JavaScript timer

When writing JavaScript code, you may want to delay the execution of functions. Learn how to use setTimeout and setInterval to schedule functions in the future

setTimeout()

While writingJavaScriptCode, you may want to delay execution of the function.

This is worksetTimeout. You specify a callback function to execute later, and specify a value that represents the time (in milliseconds) that you want it to run later:

setTimeout(() => {
  // runs after 2 seconds
}, 2000)

setTimeout(() => { // runs after 50 milliseconds }, 50)

This grammar defines a new function. You can call any other functions you need in it, or you can pass an existing function name and a set of parameters:

const myFunction = (firstParam, secondParam) => {
  // do something
}

// runs after 2 seconds setTimeout(myFunction, 2000, firstParam, secondParam)

setTimeoutReturns the timer ID. It is usually not used, but you can store this ID, if you want to delete the function execution of this plan, you can clear it:

const id = setTimeout(() => {
  // should run after 2 seconds
}, 2000)

// I changed my mind clearTimeout(id)

Zero delay

If you specify the timeout delay as0, The callback function will be executed as soon as possible, but after the current function is executed:

setTimeout(() => {
  console.log('after ')
}, 0)

console.log(’ before ')

Will printbefore after.

By queuing functions in the scheduler, you can avoid blocking the CPU when performing heavy tasks and performing other functions when performing heavy calculations, which is particularly useful.

Some browsers (IE and Edge) implementsetImmediate()A method with the same function, but this is not a standard method,Not available on other browsers. But this is a standard feature in Node.js.

setInterval()

setIntervalIs similar tosetTimeout, The difference is: it will not run the callback function once forever at the specific time interval you specify (in milliseconds), but once forever:

setInterval(() => {
  // runs every 2 seconds
}, 2000)

The above function runs every 2 seconds, unless you tell it to stop running, useclearInterval, The time interval ID that passed it to itsetIntervalcome back:

const id = setInterval(() => {
  // runs every 2 seconds
}, 2000)

clearInterval(id)

Phone calls are very commonclearIntervalIn the setInterval callback function, make it automatically determine whether it should run again or stop. For example, unless App.somethingIWait has a value, this code will run somethingarrived:

const interval = setInterval(() => {
  if (App.somethingIWait === 'arrived') {
    clearInterval(interval)
    return
  }
  // otherwise do things
}, 100)

Recursive setTimeout

setIntervalStart a function every n milliseconds, regardless of when the function has finished executing.

If a function always takes the same amount of time, there is no problem:

setInterval working fine

Functions may require different execution times, depending on network conditions, for example:

setInterval varying duration

Maybe the long execution will overlap with the next execution:

setInterval overlapping

To avoid this, you can schedule the recursive setTimeout to be called when the callback function completes:

const myFunction = () => {
  // do something

  setTimeout(myFunction, 1000)
}

setTimeout( myFunction() }, 1000)

To achieve this situation:

Recursive setTimeout

setTimeoutwithsetIntervalAvailable atNode.js,byTimer module.

Node.js also providessetImmediate(), Which is equivalent to usingsetTimeout(() => {}, 0), Mainly used in conjunction with the Node.js event loop.

Download mine for freeJavaScript beginner's manual


More js tutorials: