43

I want a jQuery countdown:

  1. It starts counting after page download finishes
  2. After counting to 0 it redirects to a url

How can I do that?

SaidbakR
  • 13,303
  • 20
  • 101
  • 195
Mostafa Elkady
  • 5,645
  • 10
  • 45
  • 69

9 Answers9

136

I thought I would break this up a bit and provide something that does both countdown, and redirection. After all, you may want to countdown and manipulate the DOM instead tomorrow. As such, I've come up with the following jQuery plugin that you can use, and study:

// Our countdown plugin takes a callback, a duration, and an optional message
$.fn.countdown = function (callback, duration, message) {
    // If no message is provided, we use an empty string
    message = message || "";
    // Get reference to container, and set initial content
    var container = $(this[0]).html(duration + message);
    // Get reference to the interval doing the countdown
    var countdown = setInterval(function () {
        // If seconds remain
        if (--duration) {
            // Update our container's message
            container.html(duration + message);
        // Otherwise
        } else {
            // Clear the countdown interval
            clearInterval(countdown);
            // And fire the callback passing our container as `this`
            callback.call(container);   
        }
    // Run interval every 1000ms (1 second)
    }, 1000);

};

// Use p.countdown as container, pass redirect, duration, and optional message
$(".countdown").countdown(redirect, 5, "s remaining");

// Function to be called after 5 seconds
function redirect () {
    this.html("Done counting, redirecting.");
    window.location = "http://msdn.microsoft.com";
}
Sampson
  • 265,109
  • 74
  • 539
  • 565
  • mmm, "setInerval -> setInterval". It would be included in such a case "clearInterval"? – andres descalzo Jan 14 '10 at 13:25
  • @andres, I just added a handler for the Interval for use in `clearInterval(countdown)`. – Sampson Jan 14 '10 at 13:26
  • 1
    @JonathanSampson, nice script. One question: how can we reset, stop and start the countdown programmatically? For example, I would like to **reset** `count` back to 10 when `(count == 0)` and also **stop** the timer for a indefinite amount of time, and **restart** the timer programmatically later. – skyork Aug 15 '12 at 03:22
  • Hi, does anybody now how to cancel this timer? – André Oliveira May 17 '16 at 02:17
  • @André You want to cancel, or pause/resume? – Sampson May 18 '16 at 06:03
  • Hi Sampson, i wanted to cancel, so i created the var countdown as a global, them i just called the clearInterval(countdown), is this the right way to do it? – André Oliveira May 23 '16 at 19:44
20

I have create a countdown script using JQUERY, CSS and HTML. Here is my full source code. Demo link also available.

CSS Part:

<style type="text/css">
    body{ font-family: verdana; font-size:12px; }
    a{text-decoration: none;color:blue;font-weight: bold;}
    a:hover{color: gray;font-weight: bold;}
    div#my-timer{width: 400px;background: lightblue; margin:  0 auto;text-align: center;padding:5px 0px 5px 0px;}
</style>

Jquery Part:

<script type="text/javascript" src="js/jquery-1.4.2.js"></script>
    <script type="text/javascript">
        var settimmer = 0;
        $(function(){
                window.setInterval(function() {
                    var timeCounter = $("b[id=show-time]").html();
                    var updateTime = eval(timeCounter)- eval(1);
                    $("b[id=show-time]").html(updateTime);

                    if(updateTime == 0){
                        window.location = ("redirect.php");
                    }
                }, 1000);

        });
    </script>

HTML Part:

<div id="my-timer">
        Page Will Redirect with in <b id="show-time">10</b> seconds        
</div>

Demo Link: http://demos.coolajax.net/php/redirect

I hope this code will be a helpful one for you.

Tarek
  • 3,810
  • 3
  • 36
  • 62
12

Are you sure, you want to use Javascript for this? You might just go with plain HTML:

<meta http-equiv="refresh" content="NUMBER_OF_SECONDS_TO_WAIT; URL=http://REDIRECT_URL/">

Put this in the header and the forward will even work on browsers without Javascript enabled.

nfechner
  • 17,295
  • 7
  • 45
  • 64
  • if there is any image or problem loading the page and makes later to finish, "" NUMBER_OF_SECONDS_TO_WAIT "countdown continues or is expected to finish loading the page? – andres descalzo Jan 14 '10 at 13:20
5

Here's my example based off of Jonathan Sampson's example. Here's the jsfiddle link. http://jsfiddle.net/njELV/1/

jQuery:

var countdown = {
    startInterval : function() {
        var count = 1800; // 30 minute timeout
        var currentId = setInterval(function(){
            $('#currentSeconds').html(count);
            if(count == 30) { // when there's thirty seconds...
                $('#expireDiv').slideDown().click(function() {
                        clearInterval(countdown.intervalId);
                        $('#expireDiv').slideUp();                      
                        window.location.reload();
                        //or whatever you'd like to do when someone clicks on the div (refresh your session etc).
                });
            }
            if (count == 0) {
                window.location.href = '/logout.php';
            }
            --count;
        }, 1000);
        countdown.intervalId = currentId;
    }
};
countdown.startInterval();

/*
Then each time an ajax call is made to fetch a page
*/
if(typeof countdown.oldIntervalId != 'undefined') {
        countdown.oldIntervalId = countdown.intervalId;
        clearInterval(countdown.oldIntervalId);
        countdown.startInterval();
        $('#expireDiv').slideUp();
    } else {
        countdown.oldIntervalId = 0;
    }

CSS:

#expireDiv {
    width: 100%;
    text-align: center;
    background-color: #63AFD0;
    padding: 10px;
    margin: 0;
    border: 1px solid #024A68;
    color: #024A68;
    font-weight: bold;
    font-size: 125%;
    box-shadow: -1px -1px 5px 1px #5E8C9E inset;
    -moz-box-shadow: -1px -1px 5px 1px #5E8C9E inset;
    -webkit-box-shadow: -1px -1px 5px 1px #5E8C9E inset;
    display:none;
    cursor: pointer;
}

HTML:

<div id="expireDiv">
    Your session is about to expire. You will be logged out in <span id="currentSeconds"></span> seconds. If you want to continue, please save your work and click <u>here</u> to refresh the page.
</div>
n0nag0n
  • 1,575
  • 1
  • 17
  • 25
2

You can use the jQuery animate function

// Enter num from and to
$({countNum: 8000}).animate({countNum: 0}, {
  duration: 8000,
  easing:'linear',
  step: function() {
    // What todo on every count
    console.log(Math.floor(this.countNum));
  },
  complete: function() {
    console.log('finished');
  }
});

http://jsbin.com/upazas/1/edit

FDisk
  • 8,493
  • 2
  • 47
  • 52
2

I have this simple solution without :

<script>
    sec = 10;
    counter = document.getElementById('counter');
    counter.innerText = sec;
    i = setInterval(function(){
        --sec;

        if (sec === 1){
            clearInterval(i);
            window.location = document.getElementById('retry').href;
        }
        counter.innerText=sec;
        },1000);
    </script>

In the example above, the redirect URL is extracted from href attribute of a hyperlink in the document, which you may replace with any value you want.

Checkout this DEMO

SaidbakR
  • 13,303
  • 20
  • 101
  • 195
1

this link useful jQuery Countdown support all language

just:)

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.countdown.js"></script>
<script type="text/javascript">
      $('#mySelector').countdown({since: new Date(2010, 12-1, 25)});
</script>
Javad Masoumi
  • 347
  • 2
  • 5
1

In Himel Khan's code example posted above, I changed

if(updateTime == 0)

to

if(updateTime <= 0)

just in case somebody hits the back button after being redirected. Otherwise it will start into negative numbers and never re-redirect.

It is important to note that you should not have the code linked on the target page with this change or it will loop refresh. If you make this change, only include the script on the page with the countdown.

I assume there is a better way to accomplish this fix so maybe somebody else could add a better solution

Thank you for the code.

wtf_lol
  • 11
  • 1
0

you can use this

<div id="counter"></div>

<script type="text/javascript" src="http://yourjavascript.com/88131111995/jquery.countdown.js"></script>

    $(document).ready(function () {
     $('#counter').countdown({
        until: 5,
        compact: true,
        onExpiry: function() { alert('bye!!'); }
      });
   });
Azam Alvi
  • 6,918
  • 8
  • 62
  • 89