Basic Javascript loading message while js processing completes

前端 未结 3 1194
闹比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 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.

提交回复
热议问题