MintY
MintY

Reputation: 643

How to delay the execution of the javascript function

here i am trying to execute the JavaScript function with 6 seconds of delay. I am executing the javascript function at body onload. I am not able to get how to five the delay for function execution...

How can i do this?

Here is my javascript snippet

Code:

function hideDiv() { 
    if (document.getElementById) { 
        document.getElementById('div').style.visibility = 'hidden'; 
    } 
} 

the function hideDiv should execute after 6 seconds

Upvotes: 0

Views: 125

Answers (3)

Math chiller
Math chiller

Reputation: 4167

use the setTimeout function like so:

setTimeout(hideDiv, 6000);

Upvotes: 0

jfriend00
jfriend00

Reputation: 708136

You use setTimeout to schedule a javascript function to run sometimes in the future.

setTimeout(hideDiv, 6000);

See MDN for documentation on setTimeout(). The first argument is a reference to the function you want it to execute. The second argument is milliseconds of delay.


Keep in mind that this will not stop other javascript that comes after this statement from executing. That will continue to execute immediately. It will schedule that particular function to run on it's own at the allotted time in the future. So, this is not like sleep() in other languages. It does not stop execution for 6 seconds. Instead, it schedules this particular function to run later, but continues executing the rest of your javascript.

So, if you had this code:

setTimeout(hideDiv, 6000);
document.getElementById("hello").style.color = "red";

The color would change immediately and hideDiv() would be called in 6 seconds.

Upvotes: 2

Mr.G
Mr.G

Reputation: 3569

Try this:

setTimeout(functionName,5000);

Upvotes: 1

Related Questions