Basic Javascript loading message while js processing completes

前端 未结 3 1156
闹比i
闹比i 2021-01-13 04:43

Im sure this has been asked 1000 times before, basically all I want to do is change the content of an element of the page to display a loading message while my other javascr

相关标签:
3条回答
  • 2021-01-13 04:47

    What would be nice if you could do would be to call the showMessage function asynchronously. In other languages, you could do this with threads, and in HTML5 you can do this with workers, which are designed exactly for this sort of thing, but for right now you can most simply just use setTimeout, which makes the code in the first argument execute after a certain amount of time, allowing the current code to execute before it does.

    Change

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

    to

       onclick="showMessage; setTimeout(wasteTime,5);"> 
    
    0 讨论(0)
  • 2021-01-13 05:04

    Your pausecomp(3000) is essentially blocking the browser from redrawing because of the while loop. I would do something like this instead :

    function wasteTime(){
        setTimeout(runNext, 3000);
    }
    
    function runNext(){
         alert("marvelous!");
    }
    
    0 讨论(0)
  • 2021-01-13 05:12

    It sounds like you're coming up against the fact that Javascript is single-threaded, but browsers are not.

    Basically, you can't have multiple pieces of Javascript running at once. However, the browser still has to do things outside of executing Javascript and proceeds to do so when it can. The problem is that whether modifying the DOM is synchronous (i.e. JS execution stops until it's done) or asynchronous (JS execution continues) isn't defined. Most browsers do the latter. But JS execution still has a quite high priority and a lot of DOM updates get deferred until the JS execution has to stop and wait. An alert box is an excellent example because it is waiting for user input.

    The way to do what you want to do is to advantage of setTimeout() which lets the current piece of JS finish, the browser can then finish updating the DOM, and then it can execute JS waiting to run on a timeout.

    0 讨论(0)
提交回复
热议问题