john-smilga/node-express-course

server.listen not allowing settimeout to work

Opened this issue · 3 comments

I am going through @john-smilga Nods-JS Course , and currently I am on module 'http'.
Below is a simple code which I wrote :-

var http = require('http');
var server = http.createServer(function (req,res) {
  res.end("Hello World") 
})

server.listen(5000);



setTimeout(() => {server.close() } ,4000);   // put anytime duration here 

The behaviour which I expected was that server should stay on for 4 seconds and then closes. But rather what is happening is that server stays on indefinitely and we can do anything, however when we leave server idle for 4 seconds, after that if we reload or do anything then the timer of 4 seconds starts and after that server closes.
Means from 0 to N seconds I kept on working, then left idle for 4 seconds, on 24th second I reloaded again and then on 29th second the server is closing.

Why is it happening like that. Basically settimeout will move to call queue after 5 seconds and then it should be moved to call stack by event loop and close the server as soon as it goes idle.We can put anytime duration in timeout we have to wait leave server idle for that duration for the settimeout to begin and after that 5 seconds it take to close it.
Why is it behaving so ?

The code is Working , you can verify this by testing if the server is able to close by calling the server.close() or else you can also check that server closes or not by adding add a 4-second countdown before closing the server.

here is the code

var http = require('http');
var server = http.createServer(function (req,res) {
  res.end("Hello World");
});

server.listen(5000);

var count = 4;
var countdownInterval = setInterval(function() {
  console.log(count);
  count--;
  if (count === 0) {
    clearInterval(countdownInterval);
    server.close(function() {
      console.log("Server closed");
    });
  }
}, 1000);

Hey, Although it's been so long but I checked your code and it's working perfectly fine. I have added some logs you may run it and check now.

var http = require('http');
var server = http.createServer(function (req, res) {
    res.end("Hello World")
})

server.listen(5000, () => {
    console.log("Server has started")
    console.time("Time taken to execute the code")
});

setTimeout(() => {
    server.close(() => {
        console.log("Server has stopped")
        console.timeEnd("Time taken to execute the code")
    })
}, 5000);   // it takes 5.00X seconds to execute the complete code.

Thanks 🙏