How can I get an element's innerHTML to update

2019-02-27 08:31发布

问题:

I have a web page with a text box. When entering in a .js file name into the box and clicking the Execute button, the file given will be loading via AJAX and eval()'d.

Also on this page is an empty <div> for used as output. If the file that is loaded needs to print something to the screen, it adds it to the div's innerHTML.

When adding text to the innerHTML, it usually doesn't render on the screen until the Javascript is completed, which is fine, except for the fact that, sometimes, the Javascript file performs heavy calculations which can take upwards to a minute to complete, and it would be useful to be able to see the output as it was executing.

Is there any way to "refresh" the document?

回答1:

You can use setTimeout:

div.innerHTML = html;
setTimeout( function(){
   doHeavyCalculations();
}, 35);

http://jsfiddle.net/YKEKK/



回答2:

I would try solving this using setTimeout.

function performInitialHtmlRender() {
    /// This sets the innerHtml that you want the user to see
    /// While you are performing the calculations
}

function performExpensiveCalculationsAndRender() {
    // This is the really expensive function that
    // you want to run once the browser has rendered 
    // the initial HTML
}

performInitialHtmlRender();
setTimeout(performExpensiveCalculationsAndRender(), 0);