codesmith
1/11/2020 - 5:04 PM

EventEmitterで一定間隔で連続実行するClock Class

const EventEmitter = require('events');

const Clock = class extends EventEmitter {
  constructor() {
    super();
    this.interval = 2000; // 2秒間隔
    this.timer = null;
 }
  start() {
    if (this.timer) {
      this.stop();
   }
    this.timer = global.setInterval(() => {
      this.emit('tick', "Hello World!");
   }, this.interval);
 }
  stop() {
    if (!this.timer) {
      return;
   }
    global.clearInterval(this.timer);
    this.timer = null;
 }
};
module.exports = Clock;
const Clock = require('.Clock');

var i = 0;
var clock = new Clock();

// message にはemit() の第2引数が渡される。
clock.on('tick', (message) => {
  console.log(++i, message);
  if (i > 3) {
    clock.stop();
 }
});
clock.start();

// $ node index.js
// 1 Hellow World!
// 2 Hellow World!
// 3 Hellow World!
// 4 Hellow World!