I am trying to start a timer with a click event and be able to reset the timer back from zero if the same button is pressed but every time I press the button that initiates the setInterval it seems to be creating a new interval and not reseting the one that was already creating. Can someone help please? This is my code:
startbtn.addEventListener('click', function(e) { clearInterval(timer); var count = 0; var timer = setInterval(function() { count++; testlbl.text = count; if (count === 10){ clearInterval(timer); testlbl.text = 'stopped'; } stopbtn.addEventListener('click', function(e) { clearInterval(timer); testlbl.text = 'stopped by button'; }); },1000); });
1 Answer
Accepted Answer
Try this:
var timer; startbtn.addEventListener('click', function(e) { if(timer) { clearInterval(timer); timer = null; } var count = 0; timer = setInterval(function() { count++; testlbl.text = count; if(count === 10) { clearInterval(timer); timer = null; testlbl.text = 'stopped'; } }, 1000); }); stopbtn.addEventListener('click', function(e) { if(timer) { clearInterval(timer); timer = null; } testlbl.text = 'stopped by button'; });
Your Answer
Think you can help? Login to answer this question!