jQuery: force display of modified dom

后端 未结 1 1742
梦谈多话
梦谈多话 2021-01-12 03:14

I\'ve run in to a problem trying to have a \'loading spinner\' on my page which runs while a table is being sorted, especially for slower clients as can take up to 10 second

相关标签:
1条回答
  • 2021-01-12 03:51

    Basically, JavaScript only has one thread for your code and UI together. That means, if your code does not relinquish control, the UI does not get shown until you do. So, in this sort of code:

    spinner_on();
    dostuff();
    spinner_off();
    

    What happens is, you insert spinner into DOM, do stuff, remove spinner, relinquish control - and UI is updated at last, with no spinner (because, at this moment, it does not exist any more).

    The basic pattern should be this:

    spinner_on();
    setTimeout(function() {
      dostuff();
      spinner_off();
    }, 0);
    

    This works as following: insert spinner into DOM, schedule something, relinquish control. UI gets updated (with spinner). Scheduled function runs: stuff gets done, spinner gets removed from DOM, control gets relinquished again. UI is updated (without the spinner).

    When you're in a debugger, the debugger rips control from your code's fingers, so you can see your spinner in the UI while your code is on hiatus.

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