I know that most probably such question has been requested several times but I have a need to show a popup or message or whatelse when a javascript function is triggered and hide it at the end.
See this simple js fiddle
That's the HTML code:
<div id='message'>Default message</div>
<input type='button' onclick='Run();' value='start'>
the div 'message' has to contain a simple text like "running" or "please wait" or ...
That's the JS function that took (delay) 3 seconds:
function Run() {
var delay = 3000; //-- 3 seconds
$( '#message' ).text('Please wait ' + delay + ' seconds...');
var start = new Date().getTime();
while (true) {
current = new Date().getTime();
if ( (start + delay) < current) {
break;
}
}
$( '#message' ).text('Done');
}
The expected behaviour is that the '#message' div contains "Please wait 3 seconds..." before to enter in the loop and "Done" string only at the end.
But that's not. Can anyone explain me (most probably "again") why or suggest a link where to find an answer?
The browser's display is only updated when the function completely finishes running. You can run the second lot of code asynchronously by using setTimeout.
Try this http://jsfiddle.net/aamir/23ZFY/11/
You have a very tight loop (while(true)...) which doesn't allow the UI to update at all. What you can do instead is this:
Basically, set the "wait message" initially and use the
setTimeout
function to update the message again after 3 seconds.Updated fiddle.
The JS event loop is too busy running
while (true) {}
to handle a DOM repaint.Use
setInterval
,setTimeout
, orrequestAnimationFrame
to trigger the next test of the time instead of a loop.… or just use
setTimeout
in the first place.