0

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
  • 192
  • 3
  • 14
  • Do you see any error in the console? – obscure Jun 26 '19 at 18:15
  • Where is all this code placed in the document? – Teemu Jun 26 '19 at 18:18
  • There's no error. The ajax request works, but the timer keeps counting. That code is placed at the bottom of the page before

    .

    – IBNets Jun 26 '19 at 18:38
  • OK, I feel foolish for not picking up on this earlier. It depends on the initial state of the timer. If I load the page with the timer paused (state saved to db), then it doesn't work. But if load it unpaused, it works. I'm still not sure why it doesn't work paused, but I think I can modify the code to handle that initial state. – IBNets Jun 27 '19 at 02:14
  • 1
    by the way you can always clearInterval before calling setInterval. your timer atleast will not run twice. – gp. Jun 27 '19 at 13:26

0 Answers0