Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js halts when console window is scrolled

If you run the following script in Node.js under Windows (at least 8)

const init = +new Date;
setInterval(() => {
    console.log(+new Date - init);
}, 1000);

and drag the thumb of a scroll bar of console window, the output of the script looks similar to

1001
2003  // long drag here
12368 // its result
13370
14372

Looks like Node.js' event loop halts during the scroll. The same thing should happen to asynchronous actions inside of http package. Thus leaving a visible terminal window is dangerous to the running server.

How do I change the code to avoid such behavior?

like image 634
polkovnikov.ph Avatar asked Dec 05 '22 12:12

polkovnikov.ph


1 Answers

NodeJS is not halted while scrolling or selecting text. The only functions that send data to stdout are halted. In your server, you are able to send log data to a file, and this way your server will not halt.

For example, see this code:

const init = +new Date;
var str=''
setInterval(() => {
    x=(+new Date - init).toString();;
    str+=x + '\n'
}, 1000);

setTimeout(function(){
    console.log(str)
},5000)

I have selected text during the first 5 seconds, and this was the result:

C:\me>node a
1002
2002
3002
4003

You can see that there is no 'pause'.

As you see, the first event loop setInterval wasn't halted, because there is no console.log inside.

Now, when you use an output file for logging, you can view live log using tail -f. This will show you each new line in the output file.

like image 78
Aminadav Glickshtein Avatar answered Dec 22 '22 16:12

Aminadav Glickshtein