What will happen when that code will be executed?

Technology CommunityCategory: Node.jsWhat will happen when that code will be executed?
VietMX Staff asked 3 years ago
Problem

What will happen when that code will be executed?

var EventEmitter = require('events');

var crazy = new EventEmitter();

crazy.on('event1', function () {
    console.log('event1 fired!');
    process.nextTick(function () {
        crazy.emit('event2');
    });
});

crazy.on('event2', function () {
    console.log('event2 fired!');
    process.nextTick(function () {
        crazy.emit('event3');
    });

});

crazy.on('event3', function () {
    console.log('event3 fired!');
    process.nextTick(function () {
        crazy.emit('event1');
    });
});

crazy.emit('event1');

It’ll get stuck! And if you wait long enough, about 30 seconds, it’ll eventually give you a “process out of memory” exception. Now, the problem is not stack overflow, it’s GC not being able to reclaim memory. Every handler has its own closure to access the crazy on the outer layer. This cost comes out of the heap. Though you might not be 100% why GC can’t successfully get the memory back, you can probably guess that the program got stuck in some even loop phase because there’s always another process.nextTick callback to be processed. So essentially, the event loop is blocked completely.