Reputation: 3719
function myfunction()
{
window.setTimeout(alert('I waited for you.'),700000000);
}
I call a function like this and I get an immediate alert saying "I waited for you".
I initially put in 7000 as the second argument, but kept pushing it up in case it was something besides seconds. I obviously want the function to do something else, but I broke it down to this simplistic example to prove to myself where the problem lies.
What's my mistake?
Upvotes: 1
Views: 116
Reputation: 707158
You have to pass a function reference, not the result of executing alert()
like this:
function myfunction() {
window.setTimeout(function() {alert('I waited for you.')},700000000);
}
When you pass alert('I waited for you.')
to setTimeout()
, you're telling the javascript interpreter to execute alert('I waited for you.')
and then pass the return result to setTimeout()
. Since that immediately executes the alert()
statement and alert doesn't return a function for setTimeout()
to use, that is clearly not what you want.
Instead, you want to pass a function reference to setTimeout()
. That can be done either with an anonymous function as in the example I provided above or it can be done with a separate named function like this:
function myAlert() {
alert('I waited for you.');
}
function myfunction() {
window.setTimeout(myAlert, 700000000);
}
Note: for more advanced usages, you can actually pass an immediately executed function to setTimeout()
as long as that function returns a function reference that setTimeout()
can call later. But, that is clearly not the usage you are attempting here with your alert()
Upvotes: 3
Reputation: 3719
I found out that if I put quotes around the first argument, it works. Here's what I actually did:
function divhide()
{
window.setTimeout("realhide()",7000);
}
function realhide(){
var mydiv = document.getElementById("mydiv");
mydiv.style.display="none";
mydiv.innerHTML="";
}
Upvotes: -2
Reputation: 20993
You can simply wrap the alert('I waited for you.')
in quotes "
as such:
function myfunction()
{
window.setTimeout("alert('I waited for you.')",7000);
}
The number is the amount of milliseconds to wait, so 7000 is 7 seconds.
See http://jsfiddle.net/Ac5Xf/
Upvotes: -1
Reputation: 207861
Wrap it in an anonymous function like:
function myfunction(){
window.setTimeout(function(){alert('I waited for you.')},700000000);
}
Here's an example jsFiddle (with a more manageable 3 second delay).
Upvotes: 2
Reputation: 76870
You should do
function makeAlert(){
alert('I waited for you.')
}
window.setTimeout(makeAlert,700000000);
otherwise the alert() is executed immediatly
Upvotes: 2
Reputation: 74036
try this
function myfunction() {
window.setTimeout( function(){alert('I waited for you.');}, 700000000);
}
In your code the function alert is called immediately. If you want to have a later execution you should pass a reference to a function and not a call of a function to setTimeout
.
Upvotes: 2