简体   繁体   中英

Javascript timer ends incorrectly

Looking for some insight on why my javascript timer doesn't work correctly. Actually it works great except for the fact that it stops with 1 second left and displays an alert. When you hit the ok button it counts down to the final second (0) and displays the alert again. I can't figure out how to stop the alert occuring at 1 second left instead of only at zero seconds...

I altered the code to run at 6 seconds instead of the full ten minutes

 function startTimer(duration, display) { var timer = duration, minutes, seconds; setInterval(function() { minutes = parseInt(timer / 60, 10); seconds = parseInt(timer % 60, 10); minutes = minutes < 10 ? "0" + minutes : minutes; seconds = seconds < 10 ? "0" + seconds : seconds; display.textContent = minutes + ":" + seconds; if (--timer < 0) { alert('Time has exceeded'); location.href = "http://nova.umuc.edu/~ct388a13/"; } }, 1000); } window.onload = function() { var tenMinutes = 60 * .1, display = document.querySelector('#time'); startTimer(tenMinutes, display); }
 <section> <p id="transactionTimer">Act fast! This transaction must be completed in <span id="time">10:00</span> minutes</p> </section>

This is because the JS is exectuted for the DOM update is shown to the user. This has to do with the JS event loop, and can be circumvented by using setTimeout with a very low timeout, ie 1ms. See the code snippet below for a working example

 function startTimer(duration, display) { var timer = duration, minutes, seconds; setInterval(function() { --timer minutes = parseInt(timer / 60, 10); seconds = parseInt(timer % 60, 10); minutes = minutes < 10 ? "0" + minutes : minutes; seconds = seconds < 10 ? "0" + seconds : seconds; display.textContent = minutes + ":" + seconds; if (timer === 0) { setTimeout(function(){ alert('Time has exceeded'); location.href = "http://nova.umuc.edu/~ct388a13/"; }, 1); } }, 1000); } window.onload = function() { var tenMinutes = 60 * .1, display = document.querySelector('#time'); startTimer(tenMinutes, display); }
 <section> <p id="transactionTimer">Act fast! This transaction must be completed in <span id="time">10:00</span> minutes</p> </section>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM