This section covers how to implement timer and sleep processing in JavaScript.
TOC
Timer
Processed after a certain time ( setTimeout, clearTimeout )
setTimeout
can be used to make the process run after a certain period of time.
const output = () => console.log(`output: ${new Date().getSeconds()} s`)
console.log(`${new Date().getSeconds()} s`)
setTimeout(output, 3000)
console.log(`${new Date().getSeconds()} s`)
55 s
55 s
output: 58 s
To cancel the process set by setTimeout
, use clearTimeout
.
const output = () => console.log(`output: ${new Date().getSeconds()} s`)
console.log(`${new Date().getSeconds()} s`)
const timeoutId = setTimeout(output, 3000)
clearTimeout(timeoutId)
console.log(`${new Date().getSeconds()} s`)
Processed at regular intervals ( setInterval, clearInterval )
setInterval
can be used to have the process run at regular intervals.
const output = () => console.log(`output: ${new Date().getSeconds()} s`)
console.log(`${new Date().getSeconds()} s`)
setInterval(output, 1000)
console.log(`${new Date().getSeconds()} s`)
1 s
1 s
output: 2 s
output: 3 s
output: 4 s
output: 5 s
:
To cancel the process set by setInterval
, use clearInterval
.
const output = () => console.log(`output: ${new Date().getSeconds()} s`)
console.log(`${new Date().getSeconds()} s`)
const intervalId = setInterval(output, 1000)
setTimeout(() => clearInterval(intervalId), 3000)
console.log(`${new Date().getSeconds()} s`)
Sleep ( using async and await )
async
await
can be used to implement a sleep process with good readability as follows.
(async () => {
const sleep = (second) => new Promise(resolve => setTimeout(resolve, second * 1000))
console.log('start')
console.log(`${new Date().getSeconds()} s`)
await sleep(1)
console.log(`${new Date().getSeconds()} s`)
await sleep(2)
console.log(`${new Date().getSeconds()} s`)
await sleep(3)
console.log(`${new Date().getSeconds()} s`)
console.log('end')
})()
start
11 s
12 s
14 s
17 s
end