Home wrapping process.nextTick leads to Maximum call stack size exceeded
Reply: 1

wrapping process.nextTick leads to Maximum call stack size exceeded

learn
1#
learn Published in 2017-12-07 09:25:16Z

I am trying to wrap process.nextTick function but that leads to recursion.

var actual = process.nextTick;

process.nextTick = function(callback)
{
console.log('next tick called');
actual.apply(this, arguments);
}

console.log('starts');
setTimeout(function(){
console.log('set timeout called');
}, 100);

this code produces

starts
next tick called
next tick called
...
RangeError: Maximum call stack size exceeded

can anyone explain the workflow???

codtex
2#
codtex Reply to 2017-12-07 10:12:48Z

I'm pretty much sure that console.log() is calling process.nextTick() and causing the recursion.

Have a look on the following example:

var counter = 0;
var actual = process.nextTick;

process.nextTick = function ()
{
    counter++;
    actual.apply(this, arguments);
}

console.log('starts ...'); // This will increment counter with 1, counter = 1
process.nextTick(function () {
    console.log('nextTick callback'); // This will increment counter with 1, counter = 3
    console.log(counter); // This will increment counter with 1, counter = 4
});
console.log('something else ...'); // This will increment counter with 1, counter = 2

/*
 *   OUTPUT 
 */
starts ...
something else ...
nextTick callback
4

Now if we remove one of the console.log() calls, we can see the following:

var counter = 0;
var actual = process.nextTick;

process.nextTick = function ()
{
    counter++;
    actual.apply(this, arguments);
}

console.log('starts ...'); // This will increment counter with 1, counter = 1
process.nextTick(function () {
    console.log(counter); // This will increment counter with 1, counter = 3
});
console.log('something else ...'); // This will increment counter with 1, counter = 2

/*
 *   OUTPUT 
 */
starts ...
something else ...
3

Note that counter is 3 now.

So my conclusion is that console.log() inside process.nextTick() overwrite function is causing the recursion.

I hope this example will help you to clear the things :)

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.308433 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO