0

我想要实现的是非常直接的,但我很困惑。我试图建立一个队列来保存医院病人,他们将登录系统,添加到阵列(FIFO),然后在一定的时间间隔后,他们应该从队列中删除。我正在使用angularjs将对象添加到数组和一个设置的时间间隔函数。创建自动化的JavaScript队列超时转移项目

(function() { 
    angular.module('patientsApp') 
    .controller('patientsController', ['$scope', function ($scope) { 

     var vm = this; 
     vm.queue = []; 

     vm.patient = {}; 

     vm.save = function() { 
      patient = angular.copy(vm.patient); 
      vm.queue.push(patient); 

      for(var i = 1; i <= vm.queue.length; i++) { 
       (function(index) { 
        setTimeout(function() { vm.queue.shift(); $scope.$apply(); }, i * 3000); 
       })(i); 
      } 

      vm.queue.forEach(function (cv, i) { 
       waitTime = 0; 
       setTimeout(function() { 
        vm.queue.shift(); 
        $scope.$apply(); 
       }, 3000 + waitTime); 
       waitTime += 3000; 
      }) 
     } 

    }]); 
})(); 

这是我的代码,我做了2个例子试图迭代数组。如果你注意到,为了使这个自动化,我已经将该方法添加到表单的add方法中。这个想法是设置一个例如3秒的间隔,但它们不应该同时触发,它们应该相距3秒。提前致谢。

回答

0

我不得不创建一个单独的按钮来处理的时间间隔。

(function() { 
    angular.module('patientsApp') 
    .controller('patientsController', ['$scope', '$interval', function ($scope, $interval) { 

     var vm = this; 
     vm.queue = []; 

     vm.patient = {}; 

     vm.timer = function() { 
      var interval = $interval(function() { 
       vm.queue.shift(); 
      }, 60000, vm.queue.length); 
     } 
     vm.save = function() { 
      patient = angular.copy(vm.patient); 
      vm.queue.push(patient); 
     } 

    }]); 
})(); 

这是最终结果。

0

请勿使用$超时,请改为使用$interval。在你的依赖

加$间隔:

.controller('patientsController', ['$scope', '$interval', function ($scope, $interval) { 

,并使用这种方式:

var index = 0; 
var interval = $interval(function(){ 
    if(vm.queue.length > index) 
     $interval.cancel(interval); //turn off the $interval at completion of all elements.. 

    vm.queue[index].shift(); 
    index++; 
}), 3000);