current position:Home>Basic API cognition of node learning

Basic API cognition of node learning

2021-08-27 05:45:02 _ Ride the wind_

This is my participation 8 The fourth of the yuegengwen challenge 23 God , Check out the activity details :8 Yuegengwen challenge


  • node Each time a complete trip is made in the event cycle , We all call it a Tick tock .
  • When a function is passed to process.nextTick() when , Indicates that the engine is at the end of the current operation ( Before the next event cycle starts ) Call this function when .( Be similar to vue Of $nextTick)
process.nextTick(() => {
    //  What needs to be done 
 Copy code 

The event loop is processing the current function code .

When the operation ends ,js The engine will run and pass it to nextTick All functions called .

This way, , You can tell js The engine needs to do something as soon as possible .

and setTimeout The function is executed at the end of the next tick , Than using nextTick() Much later .

When you want to ensure that the code has been executed in the next event loop iteration , Then use  nextTick().


  • When you want to asynchronously ( But as soon as possible ) When executing some code , One option is to use Node.js Provided  setImmediate()  function
  • As setImmediate() Any function passed in by the parameter is a callback executed in the next iteration of the event loop .
  • Pass to  process.nextTick()  In the current iteration of the event loop ( After the current operation ) Be performed . This means that it will always be  setTimeout  and  setImmediate  Before execution .
  • setTimeout  and  setImmediate All belong to macro tasks .
  • setImmediate()( It is equivalent to using  setTimeout(() => {}, 0)

setTimeout and setInterval

  • setTimeout  Will delay the function n Seconds later .

  • setTimeout  It will return to the timer id. It is not normally used , But you can save this id, And clear it when the scheduled function is to be deleted

  • setInterval  Every time n MS starts a function , and There is no need to consider when the function completes execution . In this way, it may cause , A longer execution will overlap with the next execution . To avoid that , You can schedule the recursive... To be called when the callback function completes setTimeout

copyright notice
author[_ Ride the wind_],Please bring the original link to reprint, thank you.

Random recommended