循环冻结和内存消耗

时间:2017-06-16 01:37:26

标签: javascript angularjs

我有这个代码,我想在我的应用程序上实现这个。但我想这个代码冻结了我的浏览器?实现此循环的最佳和正确方法是什么,这样我可以在不使用大量内存的情况下在浏览器上获取更新数据?

$scope.mydata = {};

function GetData(){
         $http({
            method: 'GET',
            url: 'http://localhost/Payroll-tracking-system/json/rex.json',
        }).then(function successCallback(response) {
            // this callback will be called asynchronously
            // when the response is available
            $scope.mydata = response.data;
            GetData();
        }, function errorCallback(response) {
            // called asynchronously if an error occurs
            // or server returns response with an error status.
        });

    }
    
 GetData();
 console.log($scope.mydata);

3 个答案:

答案 0 :(得分:1)

Web Worker

我建议将这个有效的无限循环移动到Web Worker,只要它们有用就可以将消息发回主线程。

用于了解它们的其他一些有用资源是:

使用worker的主要好处是代码在并行线程中以异步和有效的方式运行,从而释放主线程以进行一般用户交互。

根据要求(种类)

在您的主脚本中:

// create the blob from a string of JS code
var blob = new Blob( [ '(function(){"use strict";' +
    '...self.addEventListener("message", function(evt){...}, false);' +
    '...self.postMessage( msg );...}());' ] ),
    // get a URL for the worker
    blobURL = window.URL.createObjectURL( blob ),
    // create the worker from the URL
    wrkr = new Worker( blobURL );
// prepare to listen to the worker's messages
wrkr.addEventListener( "message", function( evt ) {
    // use evt.data passed to script from worker
}, false );
// start the worker with
wrkr.postMessage( /* any information the worker needs */ );

工作者需要如何编写,发送的消息以及如何处理这些消息的具体细节取决于应用程序的其余部分代码和功能。

工作者将无法访问主脚本中的任何函数,变量,常量等。,除非他们在初始化时将其传递给它,因此代码需要是能够独自站立。

标准的XMLHTTPRequest格式可以很好地适应外观。

在需要时使用wrkr.terminate() or self.close() methods将其删除。

答案 1 :(得分:0)

问题是,您试图在函数本身中调用GetData函数。如果要处理该函数返回的数据,则应使用其他名称调用该函数。

我为您创建了一个JSFiddle来模拟您的问题

首先,打开浏览器的控制台,然后单击JSFiddle UI上的Run。观察它输出结果(在我们的例子中是一个空对象)。

然后按照我在代码中的指示取消注释以下行(第15行)。

// Uncomment the following line and see that it runs to an infinite loop
// GetData();

你会看到它将持续运行。

希望有助于理解问题的根本原因

答案 2 :(得分:0)

您可以显示从API调用获得的数据吗?您必须启用分页,如果您不是在单个API调用中发送数据,那么您也在更新相同的变量,如果数据不断变化,您将如何使用数据。 您应该将来自api的数据添加到$ scope.data。

如果您要发送分页,那么只有在有更多可用结果时才应调用GetData()。

一个例子是:

$scope.mydata = []; //if the data is array, modify it according to your use
var start = 0;
var limit = 20;
function GetData(){
     $http({
        method: 'GET',
        params:{
          start:start,
          limit:limit
        }
        url: 'http://localhost/Payroll-tracking-system/json/rex.json',
    }).then(function successCallback(response) {
        // add the data
        $scope.mydata = $scope.mydata.concat(response.data);
        start = start + limit;
        //response.total from the api
        if(start > response.total) return; 
        else GetData();
    }, function errorCallback(response) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
    });
相关问题