In Node.js, does setTimeout () block an event loop?

If I have a simple setTimeout () function and set it to 10 seconds ...

The whole server is dead during these 10 seconds ??? It's true? This is what I heard.

+5
source share
5 answers

The answer is no . What is your Node.js link : How would you recreate the 'setTimeout' function without blocking the event loop? shown was not an setTimeoutevent loop blocking it was a cycle whilethat intentionally blocks an event loop. If you want your server to be fast, you do not want to block the event loop. An asynchronous callback, such as setTimeout, will work just fine.

- (, - ?)

+20

, , Node.js , .

, " " Node.js.

var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
    console.log("route begin");
    var start = new Date();


    setTimeout(function() {
        res.render('index', { title: start + ' - ' + new Date()});
    }, 20000);//force delay of 20 seconds.

    console.log("route end");
});

module.exports = router;

(, Firefox), URL, , Node.js, , !

, .

:

route begin at: Fri Aug 28 2015 18:35:57 GMT+0800 (CST)
route end at: Fri Aug 28 2015 18:35:57 GMT+0800 (CST)
route begin at: Fri Aug 28 2015 18:36:18 GMT+0800 (CST)
route end at: Fri Aug 28 2015 18:36:18 GMT+0800 (CST)
route begin at: Fri Aug 28 2015 18:36:20 GMT+0800 (CST)
route end at: Fri Aug 28 2015 18:36:20 GMT+0800 (CST)

, , ( Node.js setTimeout, ). 20 , - 2 .

, , !

, , , curl.

!

route begin at: Fri Aug 28 2015 18:42:51 GMT+0800 (CST)
route end at: Fri Aug 28 2015 18:42:51 GMT+0800 (CST)
route begin at: Fri Aug 28 2015 18:42:53 GMT+0800 (CST)
route end at: Fri Aug 28 2015 18:42:53 GMT+0800 (CST)
route begin at: Fri Aug 28 2015 18:42:55 GMT+0800 (CST)
route end at: Fri Aug 28 2015 18:42:55 GMT+0800 (CST)
+4

. setTimeout , . (, setTimeout), ,

+2

, , , , , setTimeout . , OP wait, setTimeout. wait - - setTimeout .

+2

, -, setTimeout while.

, :

var express = require('express')
var app = express()

function setTimeoutAsync (callback, time) {
  setTimeout(function () {
    callback()
  }, time)
  return 0
}

app.get('/', function (req, res, next) {
    console.log("route begin")
    var start = +new Date()
    setTimeoutAsync(function () {
      console.log("route done")
      res.json({ delay: ((+new Date()) - start) + 'ms' })
    }, 5000)
    console.log("route end")
});

app.listen(8000) 

:

route begin // first page
route end
route begin // second page
route end
route begin // third page
route end
route done // first render
route done // second render
route done // third render

:

https://www.journaldev.com/7462/node-js-architecture-single-threaded-event-loop

https://nodejs.org/en/docs/guides/blocking-vs-non-blocking/

0

All Articles