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