0

So basically I want to show a countdown, maybe from one minute or so and then right when the countdown reaches zero I want to run a jQuery function.

So let's say the countdown starts at 1 minute.

So I want to run a function called updateEntry() after the user has essentially spent 1 minute on the page. I've seen people use setTimeout, would I simply put my function definition there or would I call the function there? Also how would I go about synchronizing the countdown with setTimeout

Maaz
  • 4,193
  • 6
  • 32
  • 50
  • I think this is what you're looking for [JQuery Countdown with callback][1] [1]: http://stackoverflow.com/questions/2064186/how-can-i-make-a-jquery-countdown – ilias Dec 18 '13 at 20:33

2 Answers2

1

Here's one way to do it:

function doCountdown(time, cb) {
    $("#countdown").text(time);
    if (time <= 0)
        cb();
    else
        setTimeout(function() {
            doCountdown(time-1, cb);
        }, 1000);
}

doCountdown(60, updateEntry);

Demo: http://jsfiddle.net/Dgj63/

The above assumes the existence of an element on the page with id="countdown" (which you can style however you wish) for display of the number of seconds left, though if you wanted to run multiple countdowns on the same page you could pass the element id into the function as a parameter rather than hardcoding it inside the function. And of course it assumes your updateEntry() function is defined. Put the code in a script element at the end of the page, or wrap it in a document ready handler as shown in my fiddle.

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
1

Here is a working jSFiddle: http://jsfiddle.net/ZNYX5/1/

HTML (just for example):

<span><span>

jQuery:

var count = 60;

$("span").text(count);

var myTimer = setInterval(function(){
    if(count > 0){
        count = count - 1;
        $("span").text(count);
    }
    else {
       clearInterval(myTimer);
       alert("I'm done counting down!"); 
    }
},1000);

Just change the alert("I'm done counting down!"); to a call to your function.

FastTrack
  • 8,810
  • 14
  • 57
  • 78
  • is it possible to have a "cancel" button as well to simply cancel the countdown right in the middle and do nothing? – Maaz Dec 19 '13 at 22:05