jdublu
jdublu

Reputation: 187

Timer with interval alert

I have a jquery timer on my page that counts down from 10 to 0. At 5 seconds I want to show a warning message then at 0 seconds I want to show another message.

I have used the code below which will do the count down in the form field as well as give the alerts, however the countdown stops when the alerts show:

$(function(){
    var count = 10;
    countdown = setInterval(function(){
        $("#Exam_Timer").val(count + " seconds remaining!");
        if (count == 5) {
            alert('Only 5 Seconds Left');
        }   
        if (count == 0) {
            alert('Times Up')
        }
    count--;
    }, 1000);
});

Can someone let me know how I would restructure this so that the alerts do no stop the countdown?

I tried putting the alert into a separate function but that did not help. I have created a Fiddle:

http://jsfiddle.net/CQu7T/

Upvotes: 4

Views: 3030

Answers (2)

Prasenjit Kumar Nag
Prasenjit Kumar Nag

Reputation: 13461

You cant do this with alert as it stop scripts execution. However you can achieve this with jQuery UI dialogs. Check the following demo

Working Demo

Upvotes: 6

Tim
Tim

Reputation: 9489

Alerts are weird things which in essence break default browser settings (controls and scripts) when they are shown.

What you can do is placing the alert message in another element with jquery html

$(function(){
    var count = 10;
    countdown = setInterval(function(){
        $("#Exam_Timer").val(count + " seconds remaining!");
        if (count == 5) {
            $("#message").html('Only 5 Seconds Left');
        }

        if (count == 0) {
           $("#message").html('Times Up')
        }
        count--;
    }, 1000);
});

See this jsfiddle. You can make style this element with some css to make it look like a modal window.

Upvotes: 1

Related Questions