FosAvance
FosAvance

Reputation: 2469

setTimeout and window.location (location.href) not working

I want to redirect user to index.php in 5 seconds, but it redirects me right away. I don't want to use jQuery in this simple code.

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

Upvotes: 15

Views: 80592

Answers (3)

Geert
Geert

Reputation: 29

This also works:

setTimeout ("window.location='index.php'", 5000);

Upvotes: 2

Joan Caron
Joan Caron

Reputation: 1970

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>

Upvotes: 41

Birdy
Birdy

Reputation: 773

I know this thread has already been solved and its somewhat 2 years later that i have come accross this, I personally just used the example from Joan's answer and modified it to work exactly how i need it to as the location.href will not redirect the TOP or Parent page when called within an iframe.

So for anyone looking for a way to redirect after 5 seconds but within an iframe and to redirect the TOP / Parent page aswell here is how i have achieved that 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 wanted to call this by using PHP as i personally did do here is how you would use the echo command to redirect the user after 5 seconds.

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

Hope this helps anyone else searching for the same solution.

Thanks

Upvotes: 1

Related Questions