0

I have a problem with a simple javascript. I would like to display a html div for 2 seconds. I tried the following code but instead of display my div for 2 seconds on execution my div is displayed after 2 second.

//show my element document.getElementById("alertProg").style.display=block; //wait var ms=2000; ms += new Date().getTime(); while (new Date() < ms){} 

How can I solve this problem?

EDIT: the problem isn'nt only in a time delay but if I call a function between the change of display value the div isn't displayed correctly. example:

document.getElementById("alertProg").style.display='block'; myFunction(); document.getElementById("alertProg").style.display='none'; 

as result myFunction is executed but alertProg is always hidden.

2
  • 2
    var elem = document.getElementById("alertProg"); elem.style.display = 'block'; setTimeout(function() { elem.style.display = 'none'; }, 2000); Commented Mar 25, 2016 at 9:54
  • thanks Rayon Dabre Commented Mar 25, 2016 at 10:00

2 Answers 2

2

You should use setTimeout for that :

var div = document.getElementById('alertProg'); var ms = 2000; div.style.display = 'block'; setTimeout(function(){ div.style.display = 'none'; },ms); 
Sign up to request clarification or add additional context in comments.

Comments

0

You can use setTimeout function. It has two parameters. The first one is your function, the other's time (ms). When time is up which is defined, function will run.

More details here

var ms = 2000; document.getElementById("alertProg").style.display='block'; setTimeout(function(){ document.getElementById("alertProg").style.display='none'; },ms); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.