Show Message While Javascript Is Running
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 i
Solution 1:
The JS event loop is too busy running while (true) {}
to handle a DOM repaint.
Use setInterval
, setTimeout
, or requestAnimationFrame
to trigger the next test of the time instead of a loop.
functionRun() {
var delay = 3000; //-- 3 seconds
$( '#message' ).text('Please wait ' + delay + ' seconds...');
var start = newDate().getTime();
setTimeout(whenDelayIsOver, 50);
functionwhenDelayIsOver() {
if ( (start + delay) < current) {
$( '#message' ).text('Done');
} else {
setTimeout(whenDelayIsOver, 50);
}
}
}
… or just use setTimeout
in the first place.
functionRun() {
var delay = 3000; //-- 3 seconds
$( '#message' ).text('Please wait ' + delay + ' seconds...');
setTimeout(whenDelayIsOver, delay);
functionwhenDelayIsOver() {
$( '#message' ).text('Done');
}
}
Solution 2:
Try this http://jsfiddle.net/aamir/23ZFY/11/
functionRun() {
var secs = 3;
$('#message').text('Please wait '+ secs +' seconds...');
var timer = setInterval(function () {
if (secs == 1) {
clearTimeout(timer);
$('#message').text('Done');
return;
}
secs--;
$('#message').text('Please wait ' + secs + ' seconds...');
}, 1000);
}
Solution 3:
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.
functionRun() {
$('#message').text('Please wait 3 seconds...');
setTimeout(
function () {
var start = newDate().getTime();
while (true) {
current = newDate().getTime();
if ((start + 3000) < current) {
break;
}
}
$('#message').text('Done');
},0);
}
Solution 4:
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:
functionRun() {
var delay = 3000; //-- 3 seconds
$('#message').text('Please wait ' + (delay/1000) + ' seconds...');
setTimeout(function () {
$('#message').text('Done');
}, delay);
}
Basically, set the "wait message" initially and use the setTimeout
function to update the message again after 3 seconds.
Post a Comment for "Show Message While Javascript Is Running"