setTimeout attached to an onload does not work

8

I have a page in PHP that confirms or does not send the user's email through the contact page. I want it after 10 seconds (long enough for the confirmation prompt to be read), window.location is the homepage of the site. I'm trying this way:

window.onload = function(){
  setTimeout(window.location = "http://homedosite.com.br", 10000);
}

The problem is that when the confirmation page appears, simply window.location is set without waiting for the 10 seconds. What could be happening?

    
asked by anonymous 05.02.2014 / 13:56

2 answers

13

The problem is that since you have directly placed window.location = ... inside the setTimeout call, Javascript will try to evaluate the content within the parentheses immediately, so the page is already redirected.

Try switching to:

window.onload = function(){
    setTimeout(function () { window.location = "http://homedosite.com.br"; }, 10000);
}
    
05.02.2014 / 14:00
9

When executing this code, JavaScript first executes window.location = "blablabla" and takes the return value (in this case, "http://homedosite.com.br" and then sends it to setTimeout , that is, it executes before the% To do what you want, use the following code:

window.onload = function(){
  setTimeout(function () {
    window.location = "http://homedosite.com.br";
  }, 10000);
}

When you do this, you will be sending a function as a parameter to setTimeout , which will run after 10 seconds.

Read this MDN article .

    
05.02.2014 / 14:01