Skip to content

Instantly share code, notes, and snippets.

@yukidarake
Created January 12, 2016 06:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yukidarake/e66f097192fa7c680450 to your computer and use it in GitHub Desktop.
Save yukidarake/e66f097192fa7c680450 to your computer and use it in GitHub Desktop.
process.nextTickとsetImmediateの違いを理解する
'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