javascript 实现递归转非递归 并同步

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="//cdn.bootcss.com/jquery/2.2.4/jquery.js"></script>
    <script src="http://cdn.static.runoob.com/libs/angular.js/1.4.6/angular.min.js"></script>
</head>
<body>
<div ng-app="testapp" ng-controller="testctl">
    <input type="button" ng-click="one()" value="test">
</div>

<script>
    (function () {
        'use strict';
        angular
                .module('testapp', [
                ])
                .controller('testctl',['$scope','$http','$q',function ($scope,$http,$q) {

                    function addTask(fun, delay) {
                        if (typeof fun == 'function') {
                            var argu = Array.prototype.slice.call(arguments, 2);
                            var f = (function () {
                                fun.apply(null, argu);
                            });
                            return window.setTimeout(f, delay);
                        }
                        return window.setTimeout(fun, delay);
                    }

                    $scope.one = function (page) {
                        $scope.deferral_local = $q.defer();
                        page = page || 1;
                        var allpage=10;
                        $q.when($scope.splitfile(page)).then(function () {
                            page=page+1;
                            if(page<=allpage){
                                addTask($scope.one,100,page,"参数2","参数3","参数4");
                            }
                        });
                    };

                    $scope.dosomething = function (currentpage) {
                        /*
                        $http.get("/xxx.php").success(function (response) {
                            $scope.deferral_local.resolve('good');
                        });
                        */
                        $timeout(function () {
                            console.log(currentpage);
                            $scope.deferral_local.resolve('good');
                        },1000);

                        return $scope.deferral_local.promise;
                    };

                }]);
    }());

</script>


<script>

    /*
    for(var page=1;page<=10;page++){
        dosomething(page);
    }
    */

    /*
    function one(page) {
        page = page ||1;
        dosomething(page);
        page=page+1;
        if(page>10){
            return ;
        }else{
            one(page);
        }
    }
    */

</script>

</body>
</html>

发表评论

电子邮件地址不会被公开。 必填项已用*标注