Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting in 10,..9,... script

Hy,

I have a 10 sec. delay page.

var t = window.setTimeout('redirect(strUrl)', 11000);

And function redirect(strUrl) just does document.location

What would be nice if i have a little message displaying at the bottom of my page, for example: Redirecting in 10 seconds...

"one second later that setTimeout fired"

...Redirecting to destiny in 9 seconds..

etc

ps. and the dots at the end going from left to right you know it. .. ...

I myselft would probably find out how to get that every second of timeout and just with jquery altered the number ...if that would be possible at all.

like image 661
PathOfNeo Avatar asked Dec 17 '22 18:12

PathOfNeo


2 Answers

var timeout = 11; // in seconds

var msgContainer = $('<div />').appendTo('body'),
    msg = $('<span />').appendTo(msgContainer),
    dots = $('<span />').appendTo(msgContainer); 

var timeoutInterval = setInterval(function() {

   timeout--;

   msg.html('Redirecting in ' + timeout + ' seconds');

   if (timeout == 0) {
      clearInterval(timeoutInterval);
      redirect(strUrl);
   } 

}, 1000);

setInterval(function() {

  if (dots.html().length == 3) {
      dots.html('');
  }

  dots.html(function(i, oldHtml) { return oldHtml += '.' });
}, 500);

See it on jsFiddle.

If you wanted to have the second(s) thing, replace the appropriate line above with...

msg.html('Redirecting in ' + timeout + ' second' + ((timeout != 1) ? 's' : ''));

Of course, this works well with English, but probably isn't as easy with other languages.

like image 119
alex Avatar answered Dec 19 '22 08:12

alex


You can do that by creating a div you position absolutely with bottom and left coordinates, and update the text in the div by looping on each second. Something like this:

function redirect(strurl) {
  var seconds = 10;
  var div = $("<div/>").css({
    position: "absolute",
    left: "0px",
    bottom: "0px"
  }).appendTo(document.body);

  continueCountdown();

  function continueCountdown() {
    --seconds;
    if (seconds >= 0 ) {
      div.text("...Redirecting in " + seconds + " seconds...");
      setTimeout(continueCountdown, 1000);
    }
    else {
      // Redirect here
      document.location = strurl;
    }
  }
}

Live example

Note that that will be imprecise, because the timeout will not necessarily fire in exactly one second. But it'll be close.

like image 35
T.J. Crowder Avatar answered Dec 19 '22 06:12

T.J. Crowder