JayminsFakeAccount JayminsFakeAccount - 3 months ago 28
PHP Question

Hault the execution

I have a timer on my page, as timer expires it is prompting alertbox, now the problem is even after pressing OK button in alertbox it is calling again and again. Actually, I wants to redirect it to another page.

window.location="";
will work but it is going in minus timer.

HTML CODE:

<div>Registration closes in <span id="time">00:03</span> minutes</div>


JAVASCRIPT CODE:

<script src="https://code.jquery.com/jquery-3.1.0.js" integrity="sha256-slogkvB1K3VOkzAI8QITxV3VzpOnkeNVsKvtkYLMjfk=" crossorigin="anonymous"></script>

<script type="text/javascript">
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);

minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;

display.text(minutes + ":" + seconds);

if (--timer < 0) {
alert("I am an alert box!");
//window.location = "http://www.google.com";
}
}, 1000);
}

jQuery(function ($) {
var fiveMinutes = 0.5 * 5,
display = $('#time');
startTimer(fiveMinutes, display);
});
</script>

Answer

You has to save the reference of your interval to stop it when you want it. Take a look this:

var interval;
function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    interval = setInterval(function () {
        minutes = parseInt(timer / 60, 10)
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.text(minutes + ":" + seconds);

        if (--timer < 0) {
            alert("I am an alert box!");
            clearInterval(interval);
        }
    }, 1000);
}

$(function ($) {
    var fiveMinutes = 0.5 * 5,
        display = $('#time');
    startTimer(fiveMinutes, display);
});
 
<script src="https://code.jquery.com/jquery-3.1.0.js" integrity="sha256-slogkvB1K3VOkzAI8QITxV3VzpOnkeNVsKvtkYLMjfk=" crossorigin="anonymous"></script>  
<div id="time" />

But It will prefer to use this code

setTimeout(function(){ startTimer(fiveMinutes, display); }, 1000);

and then into startTimer function, depending on your logic, call again the setTimeout.

Hope It helps!