AngularJS-计算繁重的任务 [英] AngularJS - Computation-Heavy Tasks

查看:114
本文介绍了AngularJS-计算繁重的任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Angular应用程序中是否有用于处理繁重计算任务的模式? (除了仅使用$ timeout并使用0的延迟使它们退出调用堆栈吗?)即使使用$ timeout似乎也会在处理本身启动时使UI无响应.我是否需要查看Web Worker或类似的东西?那,还是有一种成角度的方式"?

Is there a pattern in Angular apps for computation-heavy tasks? (Beyond just using $timeout with a delay of 0 to let them get off the call stack?) Even using $timeout seems to make the UI unresponsive when the processing itself kicks in. Do I need to be looking at Web Workers or something like that, or is there an "Angular way?"

推荐答案

我想出了一种方法,可以通过创建特殊的循环函数来解决UI响应性问题,这些循环函数每次在循环中都使用Angular $timeout.

I came up with a way to solve my UI responsiveness problem by creating special loop functions that use an Angular $timeout each time through the loop.

app.service('responsivenessService', function($q, $timeout) {
    var self = this;

    // Works like Underscore's map() except it uses setTimeout between each loop iteration
    // to try to keep the UI as responsive as possible
    self.responsiveMap = function(collection, evalFn)
    {
        var deferred = $q.defer();

        // Closures to track the resulting collection as it's built and the iteration index
        var resultCollection = [], index = 0;

        function enQueueNext() {
            $timeout(function () {
                // Process the element at "index"
                resultCollection.push(evalFn(collection[index]));

                index++;
                if (index < collection.length)
                    enQueueNext();
                else
                {
                    // We're done; resolve the promise
                    deferred.resolve(resultCollection);
                }
            }, 0);
        }

        // Start off the process
        enQueueNext();

        return deferred.promise;
     }
     return self;
});

此映射函数返回可分配给$scope的Promise.用法类似于下划线或新浏览器中的本机Javascript数组的map()函数:

This mapping function returns a promise which can be assignable to a $scope. Usage is similar to the map() functions from Underscore or native Javascript arrays in newer browsers:

$scope.results = responsivenessService.responsiveMap(initialdata, function() {
    // Long-running or computationally intense code here
    return result;
});

原本会阻塞整个UI的代码现在似乎在后台运行(尽管本质上是一种幻想,例如在较旧的应用程序中定期调用Application.DoEvents).不错,而且通用,只要长时间运行的代码有利于循环执行map()样式的操作即可!

Code that would originally have blocked the whole UI now appears to run in the background (although essentially it's an illusion, like calling Application.DoEvents periodically in older applications). Nice and generic, as long as the long-running code is conducive to a looping map()-style operation!

这篇关于AngularJS-计算繁重的任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆