Create automatic javascript queue with time out to shift items

616 Views Asked by At

What I'm trying to achieve is very straight forward but I'm confused. I'm trying to make a queue that holds hospital patients, they will be logged in the system, added to an array (FIFO) and then after a certain interval, they should be removed from the queue. I'm using angularjs to add objects to the array and a set time interval function.

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

     }]);
})();

This is my code, I've made 2 examples trying to iterate over the array. If you notice, to make this auto, I've added the method into the add method of the form. The idea is to set an interval of for example 3 seconds, but they should not trigger at the same time, they should be 3 seconds apart from each other. Thanks in advance.

2

There are 2 best solutions below

0
On BEST ANSWER

I had to create a separate button to handle the time interval.

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

     }]);
})();

this is the final result.

0
On

Don't use $timeout, use $interval instead.

add $interval in your dependencies:

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

and use it this way:

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