How to avoid freezing the browser when doing long-running computations in Javascript

后端 未结 5 1934
慢半拍i
慢半拍i 2020-11-28 09:15

I have a web page where a javascript calculation in a function takes lot of time to finish and makes the page to freeze. What technique should I use to make sure the javascr

5条回答
  •  南笙
    南笙 (楼主)
    2020-11-28 10:00

    Let me elaborate on @jfriend00's answer by giving a concrete stripped down example. Here is a long-running JavaScript process that can be started by clicking a button. Once it runs, it freezes the browser. The process consists of a long loop that repeats some workload where one iteration takes comparatively little time.

    Due to the browser freeze, debugging a script like this is not easy. One alternative to avoid browser freeze is using a web worker. The drawback of that approach is the poor debuggabilty of web workers per se: Tools like Firebug are not supported.

    
    
        
    
    
        
    
    
    

    Using a Queue data structure (e.g. http://code.stephenmorley.org/javascript/queues/), an interval timer and some small modification to the control flow of the original process one can build a GUI that doesn't freeze the browser, leaves the process fully debuggable and even allows additional features like stepping, pausing and stopping.

    Here is how it goes:

    
    
        
        
    
    
        
        
        
        
        
    
    
    

    While this approach certainly doesn't fit all long-running scripts one can think of, it certainly can be adapted to any loop-like scenario. I'm using it to port Numenta's HTM/CLA artificial intelligence algorithms to the browser.

提交回复
热议问题