简体   繁体   中英

Prevent timer from stopping when window is inactive Javascript

Helllo, I'm making a quiz application, and want to set a timer. I want to make it in Javascript. This is my function:

function countDown(sec, elem) {
    _(elem).innerHTML = sec;
    if(sec < 1) {
        clearTimeout(timer);
        endGame ();
        return;
    }
    sec--;
    var timer = setTimeout('countDown('+sec+',"'+elem+'")',1000);
}

The problem is that, for example, for mobile Saffari browser, when you hold your finger on the screen (like scrolling effect), the timer stops, yet you can still see the questions... So, basically, you can have an unlimited time. How can I make the timer to run nomatter what?

Thank you in advance!

You can't make the time run 'no matter what' - Mobile Safari will not run setTimeout and setInterval function calls during touch events. In fact, prior to iOS6, the events are discarded completely.

You should instead sanity check with the Date constructor, and perform server-side validation. If someone really wants to cheat, they can, after all, modify your JavaScript on the client.

You could always check the Date whenever the timer event does fire. Something like:

var timerStart = function(timeLimit) {
    var remaining = timeLimit, h, m, s;
    var startTime = +new Date();/*Date.now();*/

    var instance = function() {
        if (remaining > 0) {
            remaining = timeLimit - ((+new Date()) - startTime);
            h = Math.floor(remaining / 3600000);
            m = Math.floor(remaining % 3600000 / 60000);
            s = Math.floor(remaining % 3600000 % 60000 / 1000);
            window.setTimeout(instance, 1000);
        } else {
            /* do whatever you need to do when time is up */
        }
    }

    instance();
}

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