Webworkers are the perfect way to do any processor intensive or slow operation in order to not lock up the user's browser. This library angularizes web workers
var myWorker = new Worker("doubler.js"); myWorker.onmessage = function (oEvent) { alert("Answer: " + oEvent.data); }; myWorker.postMessage($scope.value); // start the worker.
self.onmessage = function (oEvent) { self.postMessage(oEvent.data * 2); };
While this might be still occasionally necessary, it is a pain to create new files in order to get asynchronous, multi-thread execution. Often times it is only a function or a few functions that need to be run in a new thread.
angular.module('demo', ['ngWebworker']) .controller('demoCtrl', function($scope, Webworker) {});
function doubler(num) { return num * 2; } var myWorker = Webworker.create(doubler); myWorker.run($scope.value).then(function(result) { alert("Answer: " + result); });
var myWorker = Webworker.create("doubler.js"); myWorker.run($scope.value).then(function(result) { alert("Answer: " + result); });
function async(iTime, iNotices) { var iFinished = iNotices, iCalls = 0; while (iNotices--) { setTimeout(function() { notify(++iCalls); if (iCalls == iFinished) { complete(iCalls); } }, iTime * (iNotices + 1)); } } $scope.asyncProgress = 0; $scope.asyncDone = false; var myWorker = Webworker.create(async, {async: true }); myWorker.run(500, $scope.value).then(function(result) { $scope.asyncDone = true; }, null, function(progress) { $scope.asyncProgress = progress / ($scope.value) * 100; });
$scope.requireDemo = function() { var requireWorker = Webworker.create(requireSum, {async: true}); requireWorker.run($scope.numList.split(',')).then(function(result) { alert(result); }); }; function requireSum(array) { importScripts("https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.20/require.min.js"); require(['https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.0/lodash.min.js'], function(_) { return complete(_.sum(array)); }); }