Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Node.js timers module

Node.js Timers module

Java FileNode.js Built-in Modules


Node.js's timers The module provides a series of functions for executing code after a specific time or repeating code at a specified interval. These features are very useful for implementing delayed execution, periodic tasks, and timeout control.

Although timers The module is a core Node.js module, but its methods such as setTimeout() are setTimeout(), setInterval() and setImmediate() globally available and do not need to be explicitly imported.


Main timer functions

setTimeout()

setTimeout() The setTimeout() function executes a callback once after the specified number of milliseconds.

Example

// Print a message after 2 seconds

setTimeout

(

(

)

=>

{

  console.

log

(

'This message will appear after 2 seconds'

)

;

}

,

2000

)

;

Parameter Description

  1. Callback Function: the function to execute
  2. Delay: time in milliseconds (1000 ms = 1 second)
  3. Optional arguments: additional arguments passed to the callback function

Example

// Example with additional arguments

setTimeout

(

(

name

,

age

)

=>

{

  console.

log

(

`Hello, $

{

name

}

, you are $

{

age

}

years old`

)

;

}

,

1000

,

'Zhang San'

,

25

)

;

clearTimeout()

clearTimeout() Used to cancel a timer previously set by setTimeout() the function above.

Example

const

timerId

=

setTimeout

(

(

)

=>

{

  console.

log

(

'This message will not appear'

)

;

}

,

2000

)

;

clearTimeout

(

timerId

)

;

// Cancel the timer


setInterval()

setInterval() The setInterval() function repeatedly executes a callback at the specified interval in milliseconds.

Example

// Print a message every 1 second

let counter

=

0

;

const

intervalId

=

setInterval

(

(

)

=>

{

  counter

++;

  console.

log

(

`This is the $

{

counter

}

th execution`

)

;

 

if

(

counter

===

5

)

{

    clearInterval

(

intervalId

)

;

// Stop the timer

 

}

}

,

1000

)

;

clearInterval()

clearInterval() Used to stop the repeated timer previously set by setInterval() the function above.

Example

const

intervalId

=

setInterval

(

(

)

=>

{

  console.

log

(

'This message will appear repeatedly'

)

;

}

,

1000

)

;

// Stop the timer after 5 seconds

setTimeout

(

(

)

=>

{

  clearInterval

(

intervalId

)

;

}

,

5000

)

;


setImmediate()

setImmediate() The setImmediate() function executes a callback at the end of the current event loop.

Example

console.

log

(

'start'

)

;

setImmediate

(

(

)

=>

{

  console.

log

(

'Execute callback immediately'

)

;

}

)

;

console.

log

(

'End'

)

;

// Output order:

// Start

// End

// Execute callback immediately

clearImmediate()

clearImmediate() Used to cancel a timer previously set by setImmediate() the immediate callback set by it.

Example

const

immediateId

=

setImmediate

(

(

)

=>

{

  console.

log

(

'This message will not appear'

)

;

}

)

;

clearImmediate

(

immediateId

)

;


Timer execution order

Understanding the Node.js event loop is essential for mastering the execution order of timers. The following are the execution orders of several kinds of timers:

  1. Synchronous code: executed first
  2. process.nextTick(): executed immediately after the current phase ends
  3. Promise callbacks: microtask queue
  4. setImmediate(): executed after I/O callbacks
  5. setTimeout() and setInterval(): executed in the check phase

Example

console.

log

(

'start'

)

;

setTimeout

(

(

)

=>

console.

log

(

'setTimeout'

)

,

0

)

;

setImmediate

(

(

)

=>

console.

log

(

'setImmediate'

)

)

;

process.

nextTick

(

(

)

=>

console.

log

(

'nextTick'

)

)

;

Promise.

resolve

(

)

.

then

(

(

)

=>

console.

log

(

'Promise'

)

)

;

console.

log

(

'End'

)

;

// Typical output order:

// Start

// End

// nextTick

// Promise

// setTimeout

// setImmediate


Advanced usage and notes

Cancelling timers

All timer functions return a Timeout Timeout object that can be used to cancel the timer. Even if the timer has already fired, calling the cancel function is safe.

Example

const

timeout

=

setTimeout

(

(

)

=>

{

}

,

1000

)

;

clearTimeout

(

timeout

)

;

// Safe to call even if the timer has already fired

Timer precision

Node.js timers cannot guarantee exact execution times; they represent the time you must wait "at least". System load and other factors may affect the actual execution time.

Memory Leaks

Forgetting to clear setInterval() Timers are a common source of memory leaks. Make sure to clear timers when they are no longer needed.

Example

// Wrong approach - may cause a memory leak

setInterval

(

(

)

=>

{

 

// Perform some operation

}

,

1000

)

;

// Correct approach - clear the timer when appropriate

const

interval

=

setInterval

(

(

)

=>

{

 

// Perform some operation

 

if

(

someCondition

)

{

    clearInterval

(

interval

)

;

 

}

}

,

1000

)

;

Recursive setTimeout instead of setInterval

For tasks that require a fixed interval but have uncertain execution time each time, use recursive setTimeout. setTimeout compared to setInterval more reliable.

Example

function

doSomething

(

)

{

  console.

log

(

'Performing task...'

)

;

 

 

// Simulate uncertain task execution time

 

const

delay

=

Math

.

random

(

)

1000

;

 

  setTimeout

(

doSomething

,

1000

delay

)

;

}

setTimeout

(

doSomething

,

1000

)

;


Practical Application Examples

Implement a simple countdown

Example

function

countdown

(

seconds

)

{

  let current

=

seconds

;

 

  console.

log

(

`Countdown starts: $

{

current

}

seconds`

)

;

 

 

const

timer

=

setInterval

(

(

)

=>

{

    current

--;

   

   

if

(

current

<=

0

)

{

      clearInterval

(

timer

)

;

      console.

log

(

'Countdown finished!'

)

;

   

}

else

{

      console.

log

(

`Remaining time: $

{

current

}

seconds`

)

;

   

}

 

}

,

1000

)

;

}

countdown

(

5

)

;

Request timeout handling

Example

function

fetchWithTimeout

(

url

,

timeout

=

5000

)

{

 

return

new

Promise

(

(

resolve

,

reject

)

=>

{

   

const

timeoutId

=

setTimeout

(

(

)

=>

{

      reject

(

new

Error

(

`Request timed out ($

{

timeout

}

ms)`

)

)

;

   

}

,

timeout

)

;

   

    fetch

(

url

)

      .

then

(

response

=>

{

        clearTimeout

(

timeoutId

)

;

        resolve

(

response

)

;

     

}

)

      .

catch

(

error

=>

{

        clearTimeout

(

timeoutId

)

;

        reject

(

error

)

;

     

}

)

;

 

}

)

;

}

// Usage example

fetchWithTimeout

(

'https://api.example.com/data'

)

  .

then

(

data

=>

console.

log

(

data

)

)

  .

catch

(

error

=>

console.

error

(

error

)

)

;

By mastering Node.js's timers timers module, you can effectively control when code runs and implement various scheduled tasks and asynchronous control flows.

Java FileNode.js Built-in Modules