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);