Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setTimeout does not work in nodeJS

I am writing a little dynamic HTTP server based on net module (homework assignment) that sends 408 response if the server user didn't call response.end() after two seconds.

No matter what I tried, the function is not invoked. Here's another code that demonstrates what I tried to do in my program:

var NET = require("net"); 
var server = NET.createServer(function(socket){
    console.log("In connectionHandler");
    socket.on('data',function(data) {
        console.log("New data");
        var timer = setTimeout(function(end){
            console.log("INSIDE TIMEOUT FUNCTION");
            if (end) {
                return;
            }
            throw new ERROR.ServerError('408',' Request Timeout','The \
            server has timedouted');
            },10,true);
        for (var t = 0 ; t < 100000000000 ; t++){}
        clearTimeout(timer);
    })

});


server.listen(4000, function() {
    console.log("server bound");
});

So, timeout is set to 10 ms followed by a very long loop, yet this doesn't work.

Why this is happening?

like image 960
Yotam Avatar asked Jul 24 '26 17:07

Yotam


1 Answers

The callback is never called because setTimeout is asynchronous. The timer gets activated when this "turn" is over, and you clear the timeout before the end of the turn.

You should read first about javascript's event driven architecture. This tutorisal would be a good start. This is essential to solve your timeout problem.

like image 91
molnarg Avatar answered Jul 26 '26 11:07

molnarg