views:

72

answers:

3

How do I write a JavaScript timer that will automatically redirect my users to a different page when the timer expires?

+2  A: 

You should use setTimeout(). For example:

var t = setTimeout("alert('5 seconds!')",5000);

Your code should look something like this (where time is miliseconds):

function redirectTimer(url, time) {
  var t = setTimeout("window.location = '" + url + "'",time);
}

P.S. I've wrote this code on the fly and didn't test it.

Pawka
+4  A: 

@Pawka's answer is correct but you shouldn't be passing a string to setTimeout - you should use a function:

function redirectTimer(url, time)
{
    return setTimeout(function()
    {
        location.href = url
    }, time);
}
Greg
Yes, I agree with @Greg.
Pawka
+2  A: 

I think, it would be better to use Refresh Meta Tag instead of javascript. Because if javascript is turned off, this solution will stil works.

Ex.:

<http-equiv="refresh" content="5;URL=http://www.yoursite.com"&gt;
Cleiton
If you need redirect user after some his actions (clicked few buttons, selected menu item, etc.), then meta-redirect doesn't fits. JavaScript is better sollution. And at overal, in nowdays browsing with turned off JavaScript is rare case.
Pawka