【问题标题】:Create automatic javascript queue with time out to shift items创建带有超时的自动javascript队列以转移项目
【发布时间】:2016-08-17 16:56:59
【问题描述】:

我想要实现的目标非常简单,但我很困惑。我正在尝试创建一个包含医院患者的队列,他们将被记录到系统中,添加到一个数组(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 个示例来尝试遍历数组。如果您注意到,为了使这个自动,我已经将该方法添加到表单的 add 方法中。这个想法是设置一个例如 3 秒的间隔,但它们不应该同时触发,它们应该彼此相隔 3 秒。提前致谢。

【问题讨论】:

    标签: javascript angularjs javascript-objects angularjs-timeout


    【解决方案1】:

    不要使用 $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);
    

    【讨论】:

      【解决方案2】:

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

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

      这是最终结果。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-22
        • 2021-02-08
        • 2014-12-17
        • 2020-08-06
        相关资源
        最近更新 更多