如何在Javascript中进行长时间运行的计算时避免冻结浏览器

Rav*_*avi 26 javascript performance

我有一个网页,其中函数中的javascript计算需要花费大量时间才能完成并使页面冻结.我应该使用什么技术来确保在后台进行计算时javascript不会冻结浏览器?

jfr*_*d00 29

如果您只需要进行计算而不需要在长时间运行的计算期间访问DOM,那么您有两个选择:

  1. 你可以把计算分成几块,一次做一块setTimeout().在每次setTimeout()通话时,浏览器都可以自由地提供其他活动,并使页面保持活动和响应.完成最后一项计算后,即可执行结果.
  2. 您可以在现代浏览器中使用webworker在后台运行计算.当计算在webworker中完成时,它会将消息发送回主线程,然后您可以使用结果更新DOM.

这是一个相关的答案,也显示了一个示例:迭代数组而不阻止UI的最佳方法


che*_*web 5

让我通过给出一个具体的精简示例来详细说明@jfriend00 的答案。这是一个可以通过单击按钮启动的长时间运行的 JavaScript 进程。一旦运行,它就会冻结浏览器。该过程由一个长循环组成,该循环重复一些工作负载,其中一次迭代花费的时间相对较少。

由于浏览器冻结,调试这样的脚本并不容易。避免浏览器冻结的一种替代方法是使用网络工作者。这种方法的缺点是 Web Workers 本身的可调试性很差:不支持 Firebug 之类的工具。

<html>
<head>
    <script>
        var Process = function(start) {
            this.start = start;
        }

        Process.prototype.run = function(stop) {
            // Long-running loop
            for (var i = this.start; i < stop; i++) {
                // Inside the loop there is some workload which 
                // is the code that is to be debugged
                console.log(i);
            }
        }

        var p = new Process(100);

        window.onload = function() {
            document.getElementById("start").onclick = function() {
                p.run(1000000000);
            }
        }
    </script>
</head>
<body>
    <input id="start" type="button" value="Start" />
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

使用队列数据结构(例如http://code.stephenmorley.org/javascript/queues/)、间隔计时器和对原始进程的控制流的一些小的修改可以构建一个不会冻结浏览器的 GUI , 使过程完全可调试,甚至允许其他功能,如步进、暂停和停止。

这是它的过程:

<html>
<head>
    <script src="http://code.stephenmorley.org/javascript/queues/Queue.js"></script>
    <script>
        // The GUI controlling process execution
        var Gui = function(start) {
            this.timer = null; // timer to check for inputs and/or commands for the process
            this.carryOn = false; // used to start/pause/stop process execution
            this.cmdQueue = new Queue(); // data structure that holds the commands 
            this.p = null; // process instance
            this.start = start;
            this.i = start; // input to the modified process 
        }

        Gui.prototype = {
            /**
             * Receives a command and initiates the corresponding action 
             */
            executeCmd: function(cmd) {
                switch (cmd.action) {
                    case "initialize":
                        this.p = new Process(this);
                        break;
                    case "process":
                        this.p.run(cmd.i);
                        break;
                }
            },

            /*
             * Places next command into the command queue
             */
            nextInput: function() {
                this.cmdQueue.enqueue({
                    action: "process",
                    i: this.i++
                });
            }
        }

        // The modified loop-like process
        var Process = function(gui) {
            this.gui = gui;
        }

        Process.prototype.run = function(i) {
            // The workload from the original process above
            console.log(i);

            // The loop itself is controlled by the GUI
            if (this.gui.carryOn) {
                this.gui.nextInput();
            }
        }

        // Event handlers for GUI interaction
        window.onload = function() {

            var gui = new Gui(100);

            document.getElementById("init").onclick = function() {
                gui.cmdQueue.enqueue({ // first command will instantiate the process
                    action: "initialize"
                });

                // Periodically check the command queue for commands
                gui.timer = setInterval(function() {
                    if (gui.cmdQueue.peek() !== undefined) {
                        gui.executeCmd(gui.cmdQueue.dequeue());
                    }
                }, 4);
            }

            document.getElementById("step").onclick = function() {
                gui.carryOn = false; // execute just one step
                gui.nextInput();
            }

            document.getElementById("run").onclick = function() {
                gui.carryOn = true; // (restart) and execute until further notice
                gui.nextInput();
            }

            document.getElementById("pause").onclick = function() {
                gui.carryOn = false; // pause execution
            }

            document.getElementById("stop").onclick = function() {
                gui.carryOn = false; // stop execution and clean up 
                gui.i = gui.start;
                clearInterval(gui.timer)

                while (gui.cmdQueue.peek()) {
                    gui.cmdQueue.dequeue();
                }
            }
        }
    </script>
</head>
<body>
    <input id="init" type="button" value="Init" />
    <input id="step" type="button" value="Step" />
    <input id="run" type="button" value="Run" />
    <input id="pause" type="button" value="Pause" />
    <input id="stop" type="button" value="Stop" />
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

虽然这种方法肯定不适合您能想到的所有长时间运行的脚本,但它当然可以适应任何类似循环的场景。我正在使用它来将Numenta 的 HTM/CLA人工智能算法移植到浏览器。