事件驱动编程入门
学习 Node.js 中事件驱动编程的基础知识,以及它如何创建响应迅速、高效的应用程序
1const EventEmitter = require('events'); 2 3// Create an instance of EventEmitter 4const myEmitter = new EventEmitter(); 5 6// Add an event listener 7myEmitter.on('greet', (name) => { 8 console.log(`Hello, ${name}!`); 9}); 10 11// Emit the event 12myEmitter.emit('greet', 'Alice');
Output
1Time remaining: 5 seconds 2Time remaining: 4 seconds 3Time remaining: 3 seconds 4Time remaining: 2 seconds 5Time remaining: 1 second 6Countdown complete!
No configuration found for ID: d10af3a630f4ba238162f326b5bade9f32c49018efee06d9ee72920e9b3d5fb1
显示答案
以下是 index.js 的代码:
答案:使用 EventEmitter 构建动态倒计时器
1const EventEmitter = require('events'); 2 3// Create an instance of EventEmitter 4const countdown = new EventEmitter(); 5 6// Add listeners 7countdown.on('tick', (time) => { 8 console.log(`Time remaining: ${time} seconds`); 9}); 10 11countdown.on('end', () => { 12 console.log('Countdown complete!'); 13}); 14 15// Function to start the countdown 16function startCountdown(seconds) { 17 let remaining = seconds; 18 19 const interval = setInterval(() => { 20 if (remaining > 0) { 21 countdown.emit('tick', remaining); 22 remaining--; 23 } else { 24 clearInterval(interval); 25 countdown.emit('end'); 26 } 27 }, 1000); 28} 29 30// Start a 5-second countdown 31startCountdown(5);
-
Line 1: The
eventsmodule is imported. -
Line 4: An
EventEmitterinstance is created to handle countdown events. -
Lines 7–9: A listener is added for the
tickevent to log the remaining time. -
Lines 11–13: A listener is added for the
endevent to log a completion message. -
Line 16–22: The
startCountdownfunction initializes the countdown and usessetIntervalto emit thetickevent every second. -
Lines 23–26: When the countdown reaches zero, the
endevent is emitted, and the interval is cleared.
-
Line 1: The
eventsmodule is imported. -
Line 4: An
EventEmitterinstance is created to handle countdown events. -
Lines 7–9: A listener is added for the
tickevent to log the remaining time. -
Lines 11–13: A listener is added for the
endevent to log a completion message. -
Line 16–22: The
startCountdownfunction initializes the countdown and usessetIntervalto emit thetickevent every second. -
Lines 23–26: When the countdown reaches zero, the
endevent is emitted, and the interval is cleared.
显示提示
Use
require('events')to include theeventsmodule and create an instance ofEventEmitterfor managing custom events.Use
.onto define listeners for events liketick(for displaying the remaining time) andend(for signaling the countdown completion).Use
.emitto trigger thetickevent with the remaining time as an argument and theendevent when the countdown ends.Use
setIntervalto create a loop that decrements the countdown every second, stopping it withclearIntervalwhen time runs out.