简介
事件
const server = http.createServer((req,res) => {
res.statusCode = 200
res.setHeader('Content-Type','text/plain')
res.end('welcome to www.flydean.com\n')
})
const EventEmitter = require('events')
const eventEmitter = new EventEmitter()
eventEmitter.on('fire',() => {
console.log('开火')
})
eventEmitter.emit('fire')
eventEmitter.on('fire',who => {
console.log(`开火 ${who}`)
})
eventEmitter.emit('fire','美帝')
eventEmitter.on('fire',(who,when) => {
console.log(`开火 ${who} ${when}`)
})
eventEmitter.emit('fire','川建国','now')
eventEmitter.on('fire',when) => {
setImmediate(() => {
console.log(`开火 ${who} ${when}`);
});
})
eventEmitter.emit('fire','川建国','now')
事件循环
const action2 = () => console.log('action2')
const action3 = () => console.log('action3')
const action1 = () => {
console.log('action1')
action2()
action3()
}
action1()
action1
action2
action3
const action2 = () => console.log('action2')
const action3 = () => console.log('action3')
const action1 = () => {
console.log('action1')
setTimeout(action2,0)
action3()
}
action1()
action1
action3
action2
const action2 = () => console.log('action2')
const action3 = () => console.log('action3')
const action1 = () => {
console.log('action1')
setTimeout(action2,0)
new Promise((resolve,reject) =>
resolve('应该在action3之后、action2之前')
).then(resolve => console.log(resolve))
action3()
}
action1()
action1
action3
应该在action3之后、action2之前
action2
process.nextTick(() => {
console.log('i am the next tick');
})
setImmediate(() => {
console.log('I am immediate!');
})
setInterval(() => {
console.log('每隔2秒执行一次');
},2000)
const id = setInterval(() => {
console.log('每隔2秒执行一次');
},2000)
clearInterval(id)
const myFunction = () => {
console.log('做完后,隔2s再次执行!');
setTimeout(myFunction,2000)
}
setTimeout(myFunction,2000)