process.nextTick

ClusterとSocket.IO について - nodejs_jp | Google グループ

ほむほむ

hoge("a", 10);
hoge("b", 10);

function hoge(name, count) {
    var i = 0;
    (function fuga() {
        if (i < count) { 
            console.log(name + ":" + i++);
            fuga();
        } else {
            console.log(name + ":end");
        }
    })();
}

結果

a:0
a:1
a:2
a:3
a:4
a:5
a:6
a:7
a:8
a:9
a:end
b:0
b:1
b:2
b:3
b:4
b:5
b:6
b:7
b:8
b:9
b:end

nextTickに変えてみる

hoge("a", 10);
hoge("b", 10);

function hoge(name, count) {
    var i = 0;
    (function fuga() {
        if (i < count) { 
            console.log(name + ":" + i++);
            process.nextTick(fuga);
        } else {
            console.log(name + ":end");
        }
    })();
}

結果

a:0
b:0
a:1
b:1
a:2
b:2
a:3
b:3
a:4
b:4
a:5
b:5
a:6
b:6
a:7
b:7
a:8
b:8
a:9
b:9
a:end
b:end

ほむー