Skip to main content

JavaScript - Time delayed page redirect.

Dhimant

Recently in one of the project I am working on required me to do a “JavaScript” based url redirect. Originally I used a PHP header based 301 redirect

<?
header("HTTP/1.1 301 Moved Permanently");
header("Location: http://www.google.com  ");
?>

But this approach has one limitation.The limitation is that you can not send any data before the header. My client used third-party JavaScript based tracking service and he also wanted to use this service on a redirect page. ( Client demands. You deliver ). The code given below demonstrates the delayed JavaScript redirect. i.e redirect to a page after a pre specified delay in milliseconds.


<script>
window.onload = function()
{
Redirect();
}
// Redirect after 5 seconds
var count = 5;
function Redirect()
{
if (count > 0){
document.getElementById("redirect").innerHTML = count;
count = count - 1;
setTimeout("Redirect()", 1000);
}
else {
document.getElementById("redirect").innerHTML = "redirecting...";
window.open("http://www.google.com", "_self");
}
}
</script>

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="redirect.js"></script>
<title>Redirecting.....</title>
</head>
<body>

<div id="redirect"></div>

</body>
</html>