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

2
  • possible duplicate of Sleep in Javascript Commented Dec 13, 2013 at 5: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. Commented Dec 13, 2013 at 5:49

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

setTimeout(functionName,5000);

Comments

0

use the setTimeout function like so:

setTimeout(hideDiv, 6000);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.