Tom
Tom

Reputation: 845

Why setTimeout put outside a function will not be triggered?

see these 2 example

<head>
<script language="JavaScript" type="text/javascript">
var mTimer=setTimeout(foo();1000);
</script>
</head>

Other example

<head>
<script language="JavaScript" type="text/javascript">
var mTimer;
function test(){ mTimer=setTimeout(foo();1000);}
</script>
</head>

In example 1, when we load the page the mTimer=setTimeout(foo();1000); won't run

In example 2, when we click button to trigger test(); then this time mTimer=setTimeout(foo();1000); starts to run.

Why setTimeout put outside a function will not be triggered when loading the page?

Upvotes: 0

Views: 56

Answers (1)

Mulan
Mulan

Reputation: 135207

setTimeout definitely works outside of a function.

Unless foo is a function that returns another function, more than likely you want

// do this
var mTimer = setTimeout(foo, 1000);

Instead of

// don't do this
var mTimer = setTimeout(foo(), 1000);

The difference is in the first code, a reference to function foo is passed to setTimeout where as in the second code, the return value of foo() is passed to setTimeout


Run this code snippet to see it work

function foo() {
  alert("it works!");
}

setTimeout(foo, 1000);

Upvotes: 1

Related Questions