创建自动 javascript 队列,超时转移项目

Create automatic javascript queue with time out to shift items

我想要实现的目标非常简单,但我很困惑。我正在尝试制作一个队列来容纳医院患者,他们将被记录在系统中,添加到数组(FIFO)中,然后在一定时间间隔后,他们应该从队列中删除。我正在使用 angularjs 将对象添加到数组和设置时间间隔函数。

    (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 个示例来尝试遍历数组。如果您注意到,为了使它成为自动的,我已经将该方法添加到表单的添加方法中。这个想法是设置一个间隔,例如 3 秒,但它们不应该同时触发,它们应该相隔 3 秒。提前致谢。

不要使用 $timeout,改用 $interval

在你的依赖项中添加 $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);

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

(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);
         }

     }]);
})();

这是最终结果。