SetTimeout and window.location (location.href) do not work

I want to redirect the user to index.php in 5 seconds, but it redirects me right away. I do not want to use jQuery in this simple code.

<script> setTimeout(function(){location.href="index.php", 5000} ); </script> 
+7
source share
3 answers

This is the right way ...

 setTimeout(function(){location.href="index.php"} , 5000); 

You can check the docs here:

https://developer.mozilla.org/en/docs/DOM/window.setTimeout

Syntax:

 var timeoutID = window.setTimeout(func, [delay, param1, param2, ...]); var timeoutID = window.setTimeout(code, [delay]); 

Example:

 WriteDatePlease(); setTimeout(function(){WriteDatePlease();} , 5000); function WriteDatePlease(){ var currentDate = new Date() var dateAndTime = "Last Sync: " + currentDate.getDate() + "/" + (currentDate.getMonth()+1) + "/" + currentDate.getFullYear() + " @ " + currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds(); $('.result').append("<p>" + dateAndTime + "</p>"); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="result"></div> 
+23
source

This also works: setTimeout ("window.location = 'index.php'", 5000);

+2
source

I know that this topic has already been solved, and a few years later I came to this, I personally just used an example from Joan's answer and changed it to work exactly as I need it, as location.href does not redirect TOP or parent page when called inside iframe.

So, for those who are looking for a way to redirect after 5 seconds, but inside the iframe and redirect the TOP / Parent page, here is how I achieved this based on Joan's answer to the original question.

  <script type="text/javascript"> setTimeout(function(){window.top.location="index.php"} , 5000); </script> 

And if you want to call it using PHP, as I personally did here, this is how you would use the echo command to redirect the user in 5 seconds.

 echo '<script type="text/javascript">setTimeout(function(){window.top.location="index.php"} , 5000);</script>'; 

Hope this helps someone else find the same solution.

thanks

+1
source

All Articles