How to do it...

Create a class that extends EventEmitter and define two instance methods called start and stop. When the start method is called, it will trigger all listeners attached to the start event. It will keep the starting time using process.hrtime. Then, when the stop method is called, it will trigger all listeners attached to the stop event passing as an argument the difference in time since the start method was called:

  1. Create a new file named timer.js
  2. Include the events NodeJS module:
      const EventEmitter = require('events') 
  1. Define two constants that we will use to convert the returned value of process.hrtime from seconds to nanoseconds and then to milliseconds:
      const NS_PER_SEC = 1e9 
      const NS_PER_MS = 1e6 
  1. Define a class named Timer with two instance methods:
      class Timer extends EventEmitter { 
          start() { 
              this.startTime = process.hrtime() 
              this.emit('start') 
          } 
          stop() { 
              const diff = process.hrtime(this.startTime) 
              this.emit( 
                  'stop', 
                  (diff[0] * NS_PER_SEC + diff[1]) / NS_PER_MS, 
              ) 
          } 
      } 
  1. Create a new instance of the previously defined class:
      const tasks = new Timer() 
  1. Attach an event listener to the start event that will have a loop that will perform multiplications. Afterwards, it will call the stop method:
      tasks.on('start', () => { 
          let res = 1 
          for (let i = 1; i < 100000; i++) { 
              res *= i 
          } 
          tasks.stop() 
      }) 
  1. Attach an event listener to the stop event that will print the time it took for the event start to execute all its attached listeners:
      tasks.on('stop', (time) => { 
          console.log(`Task completed in ${time}ms`) 
      }) 
  1. Call the start method to trigger all start event listeners:
      tasks.start() 
  1. Save the file
  2. Open a new Terminal and run:
      node timer.js
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.157.39