简体   繁体   中英

Javascript Countdown Timer w/ Bootstrap Modal Pause

See my code below, I am trying to get the countdown timer to pause when a bs.modal is shown and to resume again once the modal is hidden. This works perfectly if the modal is opened and then closed but if you try to reopen the modal again, the timer just continues. I am probably missing something obvious but am not the best when it comes to JS.

(function countdown(remaining) {
    if(remaining === 0) {
        location.reload(true);
    }
    document.getElementById('countdown').innerHTML = remaining;

    $(document).on('shown.bs.modal', function(e) {
        console.log("modal triggered");
        clearTimeout(timeout);
    });

    $(document).on('hide.bs.modal', function(e) {
        console.log("modal closed");
        
        countdown(remaining - 1);

    });

    timeout = setTimeout(function(){
        if(remaining != 0) {
            countdown(remaining - 1);
        }
    }, 1000);

})(300);

It seems the issue with the existing code is a timing problem that results in multiple timeouts getting set simultaneously, some of which can then never be cleared because their id's get lost. It's easy to get into such a situation when you're setting up a new timeout for every iteration. So, as I mentioned, setInterval() is a better choice here. Below is a solution using setInterval(). Also note that it's written so as to ensure that any existing interval is cleared before its id is overwritten (in the function clearAndSetInterval.)

    (function (remaining) {
        var interval;
        var clearAndSetInterval = function () {
            clearInterval(interval);
            interval = setInterval(function (){
                if (remaining <= 0) {
                    clearInterval(interval);
                    location.reload(true);
                }

                document.getElementById('countdown').innerHTML = remaining;
                remaining = remaining - 1;
            }, 1000);
        };

        $(document).on('shown.bs.modal', function(e) {
            clearInterval(interval);
        });

        $(document).on('hide.bs.modal', function (e) {
            clearAndSetInterval();
        });

        clearAndSetInterval();
    })(300);

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