Best Practices For Heavy Computations in Javascript?

前端 未结 3 1785
春和景丽
春和景丽 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:11

    You should use WebWorkers

    They are really supported and they are real threads in javascript as they spawn real OS threads!

    Example

    main.js

    var heavy_process = new Worker('heavy_process.js');
    
    heavy_process.addEventListener('message', function(e) {
      // Log the workers message.
      console.log(e.data);
    }, false);
    
    heavy_process.postMessage();
    

    heavy_process.js:

    for (var series = 0; series < chartObj.masterChart.series.length; series++) {
    
      var detailData = [];
      jQuery.each(chartObj.masterChart.series[series].data, function (i, point) {
          if (point.x >= chartObj.RangeSelectedMinValue && point.x <= chartObj.RangeSelectedMaxValue) {
            detailData.push({
                x: point.x,
                y: point.y
            });
          }
      });
      chartObj.detailChart.series[series].setData(detailData);
      // you should use self.postMessage here !!!
    }
    

提交回复
热议问题