若是event loop 進入了poll階段,且代碼未設定timer,將會發生下面的狀況:node
若是event loop進入了poll階段,且代碼設定了timer:瀏覽器
setImmediate約定於setTimeout(cb,0)
path.resolve() 方法會把一個路徑或路徑片斷的序列解析爲一個絕對路徑。異步
__dirname 老是指向當前文件夾的絕對路徑socket
__filename 老是指向當前文件的絕對路徑函數
note:oop
- 執行代碼1
var fs = require('fs'); var path = require('path'); function someAsyncOperation(callback) { // 花費2ms fs.readFileSync('./read.txt', callback); } var timeoutScheduled = Date.now(); var fileReadTime = 0; setTimeout(function() { var delay = Date.now() - timeoutScheduled; console.log(`setTimeout ${delay} ms have passed since I was sheculed`); console.log('fileReaderTime', fileReadTime - timeoutScheduled); }, 10); someAsyncOperation(function() { fileReadtime = Date.now(); while (Date.now() - fileReadTime < 20) {} });
- 執行代碼2
var fs = require('fs'); var path = require('path'); function someAsyncOperation(callback) { // 花費9ms fs.readFileSync('./read.txt', callback); } var timeoutScheduled = Date.now(); var fileReadTime = 0; setTimeout(function() { var delay = Date.now() - timeoutScheduled; console.log(`setTimeout ${delay} ms have passed since I was sheculed`); console.log('fileReaderTime', fileReadTime - timeoutScheduled); }, 5); someAsyncOperation(function() { fileReadtime = Date.now(); while (Date.now() - fileReadTime < 20) {} });
- 執行代碼3
setImmediate(() =>{ console.log('setImmediate') },0) setTimeout(() =>{ console.log('setTimeout') },0) // setTimeout 和 setImmediate的執行順序不肯定 // 由於event loop的啓動也是須要時間的,可能執行到poll階段時已經超過了1ms,此時setTimeout會先執行
const fs = require('fs'); const path = require('path'); fs.readFile(path.resolve(__dirname, '/read.txt'), () => { setTimeout(() => { console.log('setTimeout'); }, 0); setImmediate(() => { console.log('setImmediate'); }, 0); }); // 執行順序是肯定的, setImmediate,setTimeout