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>

Recommended Answers

All 3 Replies

Member Avatar for stbuchok

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.

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?

Member Avatar for stbuchok

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.