setTimeout()
Runs a function once, after the given number of milliseconds has passed.
- Returns
- A timer id that you can pass to
clearTimeout().
Example
#console.log('1. Start')
setTimeout(() => {
console.log('3. 500 ms have passed')
}, 500)
console.log('2. Code doesn’t wait for the timer')Definition and usage
#The setTimeout() function schedules the given function to run after a set number of milliseconds. It doesn’t pause the program: code written after it runs immediately, and the scheduled function runs later, once the time has passed and the browser isn’t busy with other code.
It returns a timer id. Passing it to clearTimeout() cancels a call that hasn’t happened yet. This is what search-as-you-type debouncing relies on: triggering the search only once the user stops typing.
The delay is a minimum wait time, not a guarantee. Even setTimeout(fn, 0) waits until the current code finishes and every pending promise reaction has run. In tabs running in the background, the browser may stretch the delay even further.
Syntax
#setTimeout(callback)
setTimeout(callback, delay)
setTimeout(callback, delay, arg1, arg2, …)
clearTimeout(timeoutId)Parameters
#callback
function
The function to call once the time has passed.delay
optional, a number
The delay in milliseconds. Defaults to 0.arg1…argN
optional
Arguments passed to thecallbackfunction.
More examples
#const timer = setTimeout(() => console.log('Time’s up!'), 1000)
setTimeout(() => {
console.log('Response sent on time')
clearTimeout(timer)
}, 300)setTimeout(() => console.log('3. setTimeout with a 0 delay'), 0)
Promise.resolve().then(() => console.log('2. a promise’s then()'))
console.log('1. Synchronous code')Promise reactions go into the microtask queue, which is drained before the next timer runs, even one with a 0 delay.
function debounce(fn, ms) {
let timer
return (...args) => {
clearTimeout(timer)
timer = setTimeout(() => fn(...args), ms)
}
}
const search = debounce((text) => console.log('Searching:', text), 300)
search('j')
search('ja')
search('jav')
search('java')Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- Pass the function itself, not its result:
setTimeout(showHint, 1000), notsetTimeout(showHint(), 1000). - Save the timer id if you might want to cancel it, for example when the user leaves the view before it fires.
- To wait inside an
asyncfunction, wrap the timer in a promise:const wait = (ms) => new Promise((r) => setTimeout(r, ms)).
Related entries
#- setTimeout() vs setInterval()setTimeout() calls a function once after a set amount of time, while setInterval() calls it repeatedly until you stop it with clearInterval().
- setInterval()Calls a function repeatedly, at the given interval, until it’s stopped with clearInterval().
- PromiseAn object representing the result of an operation that will be available in the future: a value on success or an error.
- awaitPauses an async function until a promise settles, then returns its value or throws its error.
- () => {}An arrow function: a shorter function syntax, with no own this, and an implicit return for a single expression.
Spotted a mistake or missing an example? Write to us.