Problem with timer in JS | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Problem with timer in JS

This timer is suppose to countdown to 3 to 0 and then 4 to 0 amd then 5 to 0. But after the first function runs, some numbers get skipped and its gets crazy. any suggestions? var t = 3; var T = document.getElementsByTagName('div'); function timer(){ T[0].innerHTML = 'Time: ' + t; function count(){ t--; T[0].innerHTML = 'Time: ' + t; if(t === 0){ timeagain(); } } var interval = setInterval(count, 1000); } function timeagain(){ t = 4; T[0].innerHTML = 'Time: ' + t; function count(){ t--; T[0].innerHTML = 'Time: ' + t; if(t === 0){ timeAgain(); } } var interval = setInterval(count,1000); } function timeAgain(){ t = 5; T[0].innerHTML = 'Time: ' + t; function count(){ t--; T[0].innerHTML = 'Time: ' + t; if(t === 0){ clearInterval(interval); } } var interval = setInterval(count,1000); }

25th Jul 2018, 12:03 AM
Michael
1 Answer
+ 3
Your problem is your multiple intervals. They are asynchronous. All your three functions are running at the same time. This should be done with only one interval or at least clear the previous one before creating another. var start = 3; var t = start; var T = document.getElementsByTagName(”div”)[0]; var end = 5; var interval = setInterval(function() { T.innerHTML = ”Time: ” + t; t = t - 1; if(t == 0) { t = start + 1; } if(t > end) { clearInterval(interval); t = start; } });
25th Jul 2018, 12:27 AM
Toni Isotalo
Toni Isotalo - avatar