单击 'Cancel' 后停止调用提示框

Stop calling of prompt box once 'Cancel' is clicked

我有计时器功能,当剩余时间低于特定值时,它会向用户显示一个 prompt 框。

调用的代码片段

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;
    }

现在,这允许用户输入一个值,该值最终会增加他们的会话计时器 运行 时间。 但是当用户点击 Cancel 时,问题就来了。由于此检查驻留在间隔为 1 秒的 setTimeout 调用中(Timer),因此每秒都会调用一次警报。

我该怎么做才能阻止这种情况发生,同时又不会中断此功能,因为那样也会停止计时器

编辑 添加了完整代码

它肯定会对 post 你的完整代码有所帮助,但这里有一个快速的 JSFiddle 展示了我将如何去做:http://jsfiddle.net/eklingen/5zqecaap/1/

基本上我会和一些全局变量一起为我保存所有东西:

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
}

不过,我会用模式对话框的警报和提示来换取该计时器 运行 看看 JS 如何喜欢在显示其中一个框时冻结间隔和超时。