writing modules using new feature class

Posted on
  • Like to share how to write a module containing a class

    // modules/stopWatch.js
    
    class stopWatch {
          constructor() {
            var timeStart = 0;
            var timeStop = 0;
          }
        // Method start()
          start() { 
            this.timeStart = Date.now();
            this.timeStop = 0;
          }
        // Method stop()
          stop() { 
            this.timeStop = Date.now();
          }
          // Method duration()
          duration(){
            return this.timeStop-this.timeStart;
          }
    }
    
    exports  = stopWatch
    

    and use it.

    // projects/test_class_stopWatch.js
    
    stopWatch = new (require('stopWatch'))();
    
    function onInit(){
          stopWatch.start();
          setTimeout( function(){
            stopWatch.stop();
            console.log('duration in sec: ',
                    ( stopWatch.duration() / 1000 ).toFixed(2) );
          }, 1000);
    }
    
    setTimeout(onInit,1000);
    

    // output
    duration in sec: 1.00

  • Thanks for this. It might tidy modules up quite a bit.

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

writing modules using new feature class

Posted by Avatar for MaBe @MaBe

Actions