One occasionally needs to defer the execution of a function.
Traditional JavaScript uses timers for this purpose, with the well-known setTimeout and setInterval functions.
Node introduces another perspective on defers, primarily as means of controlling the order in which a callback executes in relation to I/O events, as well as timer events properly.

Two types of deferred event sources that give a developer the ability to schedule callback executions to occur either before, or after, the processing of queued I/O events are process.nextTick and setImmediate .

process.nextTick

The primary use of nextTick in a function is to postpone the broadcast of result events to listeners on the current execution stack until the caller has had an opportunity to register event listeners, giving the currently executing program a chance to bind callbacks to EventEmitter.emit events.

const    events    = require('events');

/* function    getEmitter()    {
    let    emitter    =    new    events.EventEmitter();
    emitter.emit('start');
    return    emitter;
} */

function    getEmitter()    {
    let    emitter    =    new    events.EventEmitter();
    process.nextTick(()    =>    {
        emitter.emit('startits');
    });
    return    emitter;
}

let    myEmitter    =    getEmitter();

myEmitter.on('startits',    ()    =>    {
    console.log('Started');
});

setImmediate

is technically a member of the class of timers, along with setInterval and setTimeout . However, there is no sense of time associated with it — there is no number of milliseconds to wait for an argument to be sent.

This method is really more of a sibling to process.nextTick , differing in one very important way: while callbacks queued by nextTick will execute before I/O and timer events, callbacks queued by setImmediate will be called after I/O events. The naming of these two methods is confusing: Node will actually run the function you give to nextTick before the one you pass to setImmediate .

This method does reflect the standard behavior of timers in that its invocation will return an object that can be passed to clearImmediate , cancelling your request to run your function later on in the same way clearTimeout cancels timers set with setTimeout .

results matching ""

    No results matching ""