Created
January 12, 2016 06:41
-
-
Save yukidarake/e66f097192fa7c680450 to your computer and use it in GitHub Desktop.
process.nextTickとsetImmediateの違いを理解する
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
var fs = require('fs'); | |
console.log('start'); | |
fs.readFile('./a.txt', function(err, data) { | |
console.log('readFile'); | |
process.nextTick(function() { | |
console.log('readFile -> nextTick'); | |
}); | |
setImmediate(function() { | |
console.log('readFile -> setImmediate'); | |
}); | |
}); | |
process.nextTick(function() { | |
console.log('nextTick'); | |
fs.readFile('./a.txt', function(err, data) { | |
console.log('nextTick -> readFile'); | |
}); | |
}); | |
setImmediate(function() { | |
console.log('setImmediate'); | |
fs.readFile('./a.txt', function(err, data) { | |
console.log('setImmediate -> readFile'); | |
}); | |
}); | |
setTimeout(function() { | |
console.log('setTimeout'); | |
fs.readFile('./a.txt', function(err, data) { | |
console.log('setTimeout -> readFile'); | |
}); | |
}, 0); | |
(function doNextTick(i) { | |
console.log(`doNextTick ${i}`); | |
if (i >= 10) { | |
return; | |
} | |
i++; | |
process.nextTick(function() { | |
doNextTick(i); | |
}); | |
})(1); | |
(function doSetImmediate(i) { | |
console.log(`doSetImmediate ${i}`); | |
if (i >= 10) { | |
return; | |
} | |
i++; | |
setImmediate(function() { | |
doSetImmediate(i); | |
}); | |
})(1); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment