0

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

jfriend00
  • 683,504
  • 96
  • 985
  • 979
MintY
  • 603
  • 5
  • 11
  • 23
  • possible duplicate of [Sleep in Javascript](http://stackoverflow.com/questions/758688/sleep-in-javascript) – Alexis King Dec 13 '13 at 05:23
  • FYI, there is NO reason to do `if (document.getElementById)`. That function exists in every browser currently in use so there is no reason to check for it. – jfriend00 Dec 13 '13 at 05:49

3 Answers3

2

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.

jfriend00
  • 683,504
  • 96
  • 985
  • 979
1

Try this:

setTimeout(functionName,5000);
Mr.G
  • 3,413
  • 2
  • 16
  • 20
0

use the setTimeout function like so:

setTimeout(hideDiv, 6000);
Math chiller
  • 4,123
  • 6
  • 28
  • 44