Best Practices For Heavy Computations in Javascript?

前端 未结 3 1779
春和景丽
春和景丽 2021-02-02 00:41

I am working on client side scripts and need to do heavy computations like pushing huge number of objects in an array, it causes JavaScript to stop response and browser hangs gi

3条回答
  •  一向
    一向 (楼主)
    2021-02-02 01:28

    You could split it in to different "threads" by using timeouts. Like so:

    var counter;
    
    function longRun(start) {
        counter = 0;
    
        for (var i = start; i < 3000; i++) {
    
            counter++;
            console.log(i);
            if (counter > 99) {
                setTimeout(function() {
                    longRun(i+1)
                }, 0);
                    console.log('counter at: ' + i + ' start fake "thread"');
                return;
            }
        }
        alert('Done!');
    }
    longRun(0);​
    

    jsFiddle example

    I guess it would prevent the warning, but I don't know how sane it really is.

提交回复
热议问题