Loading main Javascript message at js processing completion

I am sure that this was set 1000 times earlier, basically all I want to do is change the content of the page element to display the loaded message, while my other javascript code (quite resource-intensive) is completed. The problem is that the message is not displayed until the "other JS processing" is completed, thereby completely defeating its purpose. simplified example ...

<html> <head> <title> crappity crapness </title> <script type="text/javascript"> function showMessage(){ document.getElementById("content").innerHTML = "please wait while we waste some time"; } function wasteTime(){ //alert("oh joy"); pausecomp(3000); //alert("marvelous!"); } function pausecomp(millis) { var date = new Date(); var curDate = null; do { curDate = new Date(); } while(curDate-date < millis); } </script> </head> <body> <div id="content">Blah</div> <br/> <a href="http://www.google.com" onclick="showMessage(); wasteTime();"> link </a> </body> 

If I uncomment the warning “oh Joy”, the text in the div will be updated Immediatly. how can i make it work without warning?

I know that I need to skip something simple. Thanks

+4
source share
3 answers

It seems that you are faced with the fact that Javascript is single-threaded, but there are no browsers.

Basically, you cannot run multiple Javascript at the same time. However, the browser still needs to do something other than Javascript execution and continues to do so whenever possible. The problem is that the DOM modification is synchronous (i.e., JS execution stops before it is completed) or asynchronously (JS execution continues) is not defined. Most browsers do the latter. But JS execution still has a rather high priority, and many DOM updates are delayed until JS execution stops and stops. A warning is a great example because it is waiting for user input.

The way to do what you want to do is to use setTimeout() , which allows the current JS fragment to finish, then the browser can complete the DOM update, and then it can execute JS waiting to be executed by timeout.

+6
source

What would be nice if you could do this would be to call the showMessage function showMessage . In other languages, you can do this using threads, and in HTML5 you can do it with workers who are designed specifically for this kind of thing, but now you can just use setTimeout , which makes the code in the first argument execute after a certain amount of time, allowing you to execute the current code before it is executed.

Edit

  onclick="showMessage(); wasteTime();" 

to

  onclick="showMessage; setTimeout(wasteTime,5);"> 
+2
source

Your pausecomp(3000) essentially blocks browser redraws due to the while loop. I would do something like this:

 function wasteTime(){ setTimeout(runNext, 3000); } function runNext(){ alert("marvelous!"); } 
+1
source

Source: https://habr.com/ru/post/1345982/


All Articles