Hello, I decided to write a simple timer class using ES6 syntax.

There are two problems:
1. How to put the variables tick, min,seconds,minutes into the constructor, so that they would be visible inside the run() method.
2. When clicking on the stop button, the timer should stop and the link to the timer from the constructor should fall into the cleatinterval.

Using ES5, you can take out the context in a separate function and work with it, how to do the same using the new syntax?

 class Timer { constructor(){ this.timer; } run(){ let tick = 0; let min = 0 let seconds = document.getElementById('seconds'); let minutes = document.getElementById('minutes'); this.timer = setInterval( () => { tick++; if(tick == 60){ min++; tick = 0; if(min < 9){ min = '0'+min; } minutes.innerHTML = min; } if( tick < 9){ tick = '0'+tick; } seconds.innerHTML = tick; console.log('timer play'); },1000) } stop(){ console.log(this);//Ссылаетcя на btn clearInterval(this.timer);//не работает console.log('timer stop'); } } let main_timer = new Timer; btn.addEventListener('click',main_timer.run); stop.addEventListener('click',main_timer.stop); 

    1 answer 1

     constructor(){ this.timer; this.tick; this.min; this.seconds; this.minutes; } run(){ this.tick = 0; this.min = 0; this.seconds = document.getElementById('seconds'); this.minutes = document.getElementById('minutes'); this.seconds.innerHTML = ''; this.minutes.innerHTML = ''; this.timer = setInterval( () => { this.tick++; if(this.tick == 60){ this.min++; this.tick = 0; this.minutes.innerHTML = (this.min < 10)? '0' + this.min : this.min; } this.seconds.innerHTML = (this.tick < 10)? '0' + this.tick : this.tick; console.log('timer play'); }, 1000); } 

    As for the context in which run and stop will run :

     btn.addEventListener('click',main_timer.run.bind(main_timer)); stop.addEventListener('click',main_timer.stop.bind(main_timer)); 

    or

     btn.addEventListener('click', () => main_timer.run()); stop.addEventListener('click', () => main_timer.stop()); 

    or

     class Timer { ... runHandler() { return this.run.bind(this); } stopHandler() { return this.stop.bind(this); } btn.addEventListener('click', main_timer.runHandler()); stop.addEventListener('click', main_timer.stopHandler()); 
    • Is it possible to do the same thing but only without using bind, passing the context to the event? That one could just use main_timer.stop (). Like a plugin in jQuery? - JavAs
    • one
      "Like a plugin in jQuery?" - I did not understand this place. - Igor
    • What could be used just to use without context binding. for example, stop.addEventListener ('click', main_timer.stop); - JavAs
    • one
      @JavAs Without context binding, you will not have the right context. See the addition in the answer. - Igor
    • I saw everything with the update, I mean, is it possible to specify the context inside the class, and how correct is it to do so? Thanks anyway!) - JavAs