Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript setTimeout or jquery delay - neither are working for me

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.

like image 732
Catfish Avatar asked Nov 24 '10 01:11

Catfish


People also ask

Why setTimeout is not working in jquery?

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.

Why setTimeout is not working in JS?

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.

What we can use instead of setTimeout in Javascript?

The setTimeout() is executed only once. If you need repeated executions, use setInterval() instead.

What happens when setTimeout is 0?

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.


1 Answers

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);
like image 64
Ivo Wetzel Avatar answered Sep 27 '22 22:09

Ivo Wetzel