user6110729
user6110729

Reputation: 156

javascript execution events order

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.

Upvotes: 0

Views: 44

Answers (2)

Kamuran S&#246;necek
Kamuran S&#246;necek

Reputation: 3333

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);

Upvotes: 0

rsabir
rsabir

Reputation: 746

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);

Upvotes: 2

Related Questions