F
F
First name Last name2015-11-11 14:34:39
JavaScript
First name Last name, 2015-11-11 14:34:39

SetTimeout not working in nodeJs, why?

var http = require('http').createServer().listen(8080);

http.on('request', function(req, res){
    res.writeHead(200);
    res.write('START');
    setTimeout(function(){
        res.write('FINISH');
    }, 3000);
    res.end();
});

When there is a setTimeout in the code, Node will definitely throw an error. I don't know what I'm writing wrong, probably there is a syntax error maybe. Typo, maybe. Here is the error in NodeJs:
events.js:85
      throw er; // Unhandled 'error' event
            ^
Error: write after end
    at ServerResponse.OutgoingMessage.write (_http_outgoing.js:413:15)
    at null._onTimeout (C:\Users\Admin\labs\hello-world\fileReader\stream.js:7:13)
    at Timer.listOnTimeout (timers.js:119:15)

Please tell me what is the problem. Without setTimeout, everything runs smoothly.
Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Ineshin, 2015-11-11
@nickname-none

because

setTimeout(function(){
    res.write('FINISH'); // выполняется позже
}, 3000);
res.end(); // чем это

// нужно так:

setTimeout(function(){
    res.write('FINISH');
    res.end();
}, 3000);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question