1
<head>
<script type="text/javascript">
<!--
function Redirect()
{
    window.location="http://www.newlocation.com";
}

document.write("You will be redirected to main page in 10 sec.");
setTimeout('Redirect()', 10000);
//-->
</script>
</head>

1.Here my question is inside settimeout method how can we use a function to call,if we use string literal inside the single quotes i think that is represent to write the exact result like document.write("hello");now the result will be as it is inside the string..how javascript can understand that setTimeout('Redirect()', 10000); 'redirect()' as a method ,instead of writing the it as is..

<head>
<script type="text/javascript">
<!--
function Redirect() {
    window.location="http://www.tutorialspoint.com";
}
document.write("You will be redirected to our main page in 10 seconds!");
setTimeout(Redirect(), 10000);
//-->
</script>
</head>
<body>
</body>
</html>

2.When i do like this as setTimeout(Redirect(), 10000);,it is not working ...it starts to redirect the page directly instead using that settimeout it...

Bergi
  • 630,263
  • 148
  • 957
  • 1,375

3 Answers3

2

We have to pass only the function name(without brackets), write like this :

setTimeout(Redirect, 10000);

It will work.

Brijesh Bhatt
  • 3,810
  • 3
  • 18
  • 34
  • 1
    hmm ya it working,but how the string understands it as a method like this('redirect()')? – Raja Raman TechWorld Apr 30 '15 at 04:36
  • @RajaRamanTechWorld Refer this, you will understand. http://stackoverflow.com/questions/6081560/is-there-ever-a-good-reason-to-pass-a-string-to-settimeout – Brijesh Bhatt Apr 30 '15 at 04:39
  • @RajaRamanTechWorld: [arcane magic](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) – Bergi Apr 30 '15 at 04:39
1

The reason that your code is calling Redirect() immediately is because it gets evaluated when setTimeout is run.

What you can do to mitigate that is to pass an anonymous function to wrap around the method. Like so: setTimeout(function(){ Redirect(); }, 10000);

This link explains why your string "Redirect()" is evaluated as you'd expect. In short (taken from the link): String literals are evaluated in the global context, using eval. WindowTimers.setTimeout()

Priyank Sheth
  • 2,352
  • 19
  • 32
Taylor Glaeser
  • 1,338
  • 12
  • 18
0

If you write it without quotes: setTimeout(yourFunction(),1000) the browser runs that function immediately, because it is a direct call.

If you write it in quotes, the setTimeout-js-method interprets the string and call it after the timeout.

You could write setTimeout(yourFunction, 1000). That works. But consider, that in this case you can't pass any arguments.

To solve that you could write the params in a var which your timeouthandler can read in the moment it runs:

yourFunction(){
    alert(param);
} 
var param="Hello";
setTimeout(yourFunction, 1000);

Greetings André

Andre Lehnert
  • 531
  • 4
  • 9