Catfish Catfish -3 years ago 50
Javascript Question

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.

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download