I have a div
like this
<div id="sale">
........
</div>
and I tried to use both
$('#sale').delay(3000).slideDown(500);
and
setTimeout(sale(), 3000);
function sale() {
$('#sale').slideDown(500);
}
but neither of them are working. The jQuery delay says $('#sale').delay()
is not a function while the setTimeout
way says useless setTimeout
call (missing quotes). If I add double quotes around the sale()
call, it just says "Sale is not defined".
Why won't either of these work?
All I'm trying to do is make a div appear 3 seconds after the page is loaded.
if you use setTimeout the function update() has to completely finish before the next loop of time occurs, thus only 1 instance will ever be running at one time.
This is due to when a function is executed as a parameter to setTimeout , the execution context is different to the execution context of the function! Now this will print out undefined because the this keyword is executed in the context of the setTimeout function and is therefore not defined.
The setTimeout() is executed only once. If you need repeated executions, use setInterval() instead.
Late timeouts This is because even though setTimeout was called with a delay of zero, it's placed on a queue and scheduled to run at the next opportunity; not immediately. Currently-executing code must complete before functions on the queue are executed, thus the resulting execution order may not be as expected.
In case of setTimeout
you're simply doing it wrong.
setTimeout(sale(), 3000); // will call sale and use the RETURN value in the callback but sale returns undefined
You need to pass in a function:
function sale() {
$('#sale').slideDown(500);
}
setTimeout(sale, 3000); // just pass in the reference to sale()
Other possibility:
// no difference in this case
// Note: if it were obj.sale() then you would need to do this version
// otherwise sale() will get called with the this set to window
setTimeout(function(){sale()}, 3000)
And last but not least:
setTimeout(function() { $('#sale').slideDown(500); }, 3000);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With