Skip to main content

JavaScript - Time delayed page redirect.


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:  ");

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.

window.onload = function()
// 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...";"", "_self");

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

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