How to force repaint in JS?

前端 未结 3 1008
-上瘾入骨i
-上瘾入骨i 2020-12-21 23:53

What I am trying to achieve:

  1. user clicks on an element
  2. the screen shows the \"calculation in progress\" screen
  3. the system performs time-consu
3条回答
  •  盖世英雄少女心
    2020-12-22 00:39

    Because modern browsers may delay redrawing for better frame rate, versions with setTimeout may not work with too low time-outs.

    If possible you need to use requestAnimationFrame. If its not posible then @Bálint answer should work, but with much bigger timeout (in my tests in Firefox its began work with timeout near 20-30). Actual timeout value is browser dependent (and probably system dependent too)

    function very_long_func(){
       el= document.getElementById('di');
    
       requestAnimationFrame( function(){
          //edit dom for new frame;
          el.textContent = 'calculation in progress' 
          //browser will wait for this functions end, before start redraw.
          //So actual calucation must run outside of it
          setTimeout( function_with_actual_calculation, 1 ); 
    
       })
    }
    function function_with_actual_calculation(){
         //..your math here + updating textContent to "done" in the end.
    } 
    

提交回复
热议问题