I'm using a timer function with a stop/start button (mostly from the accepted answer here: javascript countdown timer with start & stop buttons). The button triggers an ajax request, and the timer stop/start happens in the callback function. It works until I start the timer at page load, in which case the start/stop button has no effect.
I've tried the function without window.onload and it works fine.
window.onload = timer;
// Counter
var createDate = parseInt(document.getElementById("create-date").innerHTML) * 1000;
var delay = parseInt(<?= Yii::$app->params['delay.update'] ?>) * 1000;
var countDownTime = createDate + delay;
var setTimer;
function timer() {
setTimer = setInterval(calcTime, 500);
function calcTime() {
var now = new Date().getTime();
var distance = countDownTime - now;
var min = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var sec = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById("timer").innerHTML = min + ":" + ("0" + sec).slice(-2);
if (distance < 0) {
clearInterval(setTimer);
document.getElementById("timer").innerHTML = "In queue...";
document.getElementById("pause-link").outerHTML = "";
}
}
}
Data-on-done call-back:
'pauseDone': function (response) {
if (response.pause == 1) {
clearInterval(setTimer);
document.getElementById("timer").innerHTML = "paused";
} else {
timer();
}
document.getElementById("pause-link").innerHTML = response.link;
},
I want the timer to count down on page load. But when I call window.onload, the function no longer responds to the callback function.
Edit: The start/stop button works if the page is loaded in the unpaused state. For some reason, it doesn't work when loaded in the paused state. Loading in the paused state results in timer() being called twice (once on pageLoad and once when "start" is clicked), after which clearInterval(setTimer) has no effect.
.
– IBNets Jun 26 '19 at 18:38