0

Hi, if I run something like this to popup an alert 2 seconds after page-load, the alert pops up instantly:

<html>
<head>
<script type="text/javascript">
setTimeout(alert('Was it worth the wait?'), 5000);
</script>
</head>
<body>
<p>Hi!</p>
</body>
</html>

whereas if I double-quote the alert function, it is functioning as usual. Can anyone explain this?

<html>
<head>
<script type="text/javascript">
setTimeout("alert('Was it worth the wait?')", 5000);
</script>
</head>
<body>
<p>Hi!</p>
</body>
</html>
2
Contributors
3
Replies
8
Views
5 Years
Discussion Span
Last Post by stbuchok
1

setTimeout expect one of 2 things, a string that it will then eval() to have the code execute, or a function.

//what you are basically doing is the following
setTimeout(function(){
    alert('some text');
}(), 5000);
//notice the () at the end of the function, this executes the function

//what you want is the following
setTimeout(function(){
    alert('some text');
}, 5000);

Another way of doing the same thing is shown below:

setTimeout(showAlert, 5000);

function showAlert()
    alert('some text');
}

//your code however was doing the equivalent of

setTimeout(showAlert(), 5000);

function showAlert()
    alert('some text');
}

//setTimeout is going to execute the return value of showAlert(), instead of executing showAlert itself.

Hope this makes sense.

0

Well, I think I got most of it. Calling alert like I did made it like a self-executing function, which will almost execute immediately, whether it is inside a setTimeOut or not, right? But why doesn't the same thing happen when it is double-quoted?

1

When it is in quotes, setTimeout uses eval. So, if you use a string instead of a function it will always wait the timeout length and then try to execute the code.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.