Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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>
like image 655
FosAvance Avatar asked Mar 27 '13 09:03

FosAvance


2 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>
like image 140
Joan Caron Avatar answered Sep 18 '22 13:09

Joan Caron


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

like image 41
Geert Avatar answered Sep 21 '22 13:09

Geert