我想在一段时间内调用一个方法.我收到堆栈溢出错误.我究竟做错了什么:
HTML:
<div ng-app="myApp" ng-controller="Ctrl"> <span>{{calledServer}}</span> </div>
JS:
var app = angular.module('myApp',[]); app.controller("Ctrl",function($scope,repo,poollingFactory) { $scope.calledServer; $scope.calledServer = poollingFactory.callFnOnInterval(function() {return repo.callServer(5);}); }); app.factory("repo",function() { function callServer(id){ return "call server with id " + id; } return { callServer: callServer }; }); app.factory("poollingFactory",function($timeout) { var timeIntervalInSec = 5; function callFnOnInterval(fn,timeInterval) { $timeout(callFnOnInterval,1000 * timeIntervalInSec); callFnOnInterval(fn,timeIntervalInSec); }; return { callFnOnInterval: callFnOnInterval }; });
jsfiddle:http://jsfiddle.net/fq4vg/423/
解决方法
您有一个不检查任何前提条件的递归调用.
您的函数的注释版本:
function callFnOnInterval(fn,timeInterval) { //Schedule a call to 'callFnOnInterval' to happen in one second // and return immediately $timeout(callFnOnInterval,1000 * timeIntervalInSec); //Immediately make a call to 'callFnOnInterval' which will repeat // this process ad-infinitum callFnOnInterval(fn,timeIntervalInSec); };
因为你不断地将调用推送到堆栈并且永远不会返回,所以它最终会耗尽空间.
由于$timeout服务返回一个promise,你可以使用它来完成更多的工作.
以下是您的服务应该是什么样子:
app.factory("poollingFactory",function ($timeout) { var timeIntervalInSec = 5; function callFnOnInterval(fn,timeInterval) { var promise = $timeout(fn,1000 * timeIntervalInSec); return promise.then(function(){ callFnOnInterval(fn,timeInterval); }); }; return { callFnOnInterval: callFnOnInterval }; });
这里有一个示例jsFiddle来演示:http://jsfiddle.net/jwcarroll/cXX2S/
关于上面代码的一些注意事项.
您正在尝试将范围属性值设置为callFnOnInterval的返回值,但这不起作用.首先,它不返回任何东西.其次,因为它是一个异步调用,它最多可以返回一个promise.