Search code examples
javascripttimerprompt

Stop calling of prompt box once 'Cancel' is clicked


I have timer function which shows the user a prompt box when the remaining time goes below a specific value.

Code Snippet of the call

function countdown(duration, display, show) {
        display.innerHTML = toHHMMSS(duration, show);
        timer = setTimeout(function(){countdown(duration, display, show);}, 1000);
        if(duration<1) {
            clearTimeout(timer);
            endSession();
        }
        duration--;
    }

    function toHHMMSS(duration, show) {
        if(duration<300 && show == 1) {
            var newMinutes = prompt("This session will expire in 5 minutes. If you want to extend, enter the minutes below");
            if(newMinutes == null) {
                /* Stop showing the alert box but without affecting the timer */
            }
            var elem = document.getElementById("timer");
            elem.style.color = "Red";
        } else {
            var elem = document.getElementById("timer");
            elem.style.color = "#3BB9FF";
        }
        var sec_num = parseInt(duration, 10); 
        var hours = Math.floor(sec_num / 3600);
        var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
        var seconds = sec_num - (hours * 3600) - (minutes * 60);

        if (hours < 10) {
            hours = "0" + hours;
        }
        if (minutes < 10) {
            minutes = "0" + minutes;
        }
        if (seconds < 10) {
            seconds = "0" + seconds;
        }
        var time = hours + ':' + minutes + ':' + seconds;
        return time;
    }

Now, this allows the user to enter a value that ultimately adds to their timer for the session to run longer. But the issue comes when the user clicks on Cancel. As this check resides in a setTimeout call with a interval of 1 sec (the Timer), the alert is getting called every second.

What do I do to stop this from happening and at the same time not break out of this function as that would stop the timer as well

EDIT Added complete code


Solution

  • It would definitely help to post your complete code, but here's a quick JSFiddle showing how I'd go about it: http://jsfiddle.net/eklingen/5zqecaap/1/

    Basically I'd go with some globals to hold everything for me:

    var timer = document.getElementById('timer');
    var tickInterval = setInterval(tick, 1000);
    var alertThreshold = 5;
    var remainingTime = 6;
    var prompted = false;
    
    function tick() {  
        // Do everything I need to here
    }
    

    I would however trade out alerts and prompts for modal dialogs to keep that timer running seeing how JS likes to freeze up intervals and timeouts when one of those boxes is being displayed.