setTimeout attached to an onload does not work

Asked

Viewed 780 times

8

I have a PHP page that confirms or does not send the user’s email through the contact page. I want after 10 seconds (long enough for the confirmation notice to be read), window.location be the home page of the site. I am trying as follows:

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

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

2 answers

13


The problem is that as you put it directly window.location = ... within the call of setTimeout, Javascript will try to evaluate the content within the parentheses immediately, and so the page is already redirected.

Try switching to:

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

9

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

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

By doing this, you will be sending a function as a parameter to the setTimeout, function to be executed after 10 seconds.

Take a look at this article of the MDN.

  • It also worked... :-D Thank you for replying!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.