Mr A
Mr A

Reputation: 1385

Delay redirect Page

I have a quick question:

I notice that there is a difference between these two codes:

function urlLogin()
{
  window.location = "http://crs.local";
}

setTimeout(urlLogin(),5000)

If I use this, I am immediately redirected.

setTimeout(function(){window.location = "http://crs.local"},5000);

But this one, it works as intended. I just want to ask the difference between the two?

Upvotes: 1

Views: 92

Answers (2)

imVJ
imVJ

Reputation: 424

The way you have it written, it's as if the output of urlLogin is the input to the first parameter of setTimeout. The first parameter should be the function, not the result of the function.

Try this instead :

setTimeout(function() {
    urlLogin();
},2000);

Upvotes: 0

Amadan
Amadan

Reputation: 198324

There should be no difference, both should be delayed 5 seconds. Are you sure you didn't have setTimeout(urlLogin(), 5000)? This seems to be a common mistake.

The correct way is what you had before you "corrected" the question :D : setTimeout(urlLogin, 5000), passing the function and not invoking it.

Upvotes: 3

Related Questions