Angularjs 如何使一个变量的值等于另一个变量的值,但延迟设置?

Angularjs 如何使一个变量的值等于另一个变量的值,但延迟设置?,angularjs,Angularjs,我的应用程序有一个$rootScope变量,当存在Ajax时,该变量被设置为非零值 请求正在进行中。我设置了一个旋转的轮子来显示这个变量的值何时大于 大于零。伪代码: $rootScope.pendingRequests > 0 then show the spinning wheel 结果是,对于非常快的请求,控制盘会短暂闪烁。我希望通过仅当请求已进行超过500毫秒时才显示控制盘来避免此闪烁。我的想法是让另一个名为$rootScope.PendingRequestsDebunced的变

我的应用程序有一个$rootScope变量,当存在Ajax时,该变量被设置为非零值 请求正在进行中。我设置了一个旋转的轮子来显示这个变量的值何时大于 大于零。伪代码:

$rootScope.pendingRequests > 0 then show the spinning wheel
结果是,对于非常快的请求,控制盘会短暂闪烁。我希望通过仅当请求已进行超过500毫秒时才显示控制盘来避免此闪烁。我的想法是让另一个名为$rootScope.PendingRequestsDebunced的变量,并让它跟随$rootScope.pendingRequests的值,如下所示:

  • 如果$rootScope.pendingRequests的值大于0且持续*至少500毫秒*s,则设置:$rootScope.PendingRequestsDebunced=$rootScope.pendingRequests

  • 如果$rootScope.pendingRequests等于0,则立即设置:$rootScope.PendingRequestsDebunced=$rootScope.pendingRequests(无延迟)


    • 我想你可以这样做

      var timeoutTask = null;
      
      $scope.showLoader = false;
      $rootScope.$watch('pendingRequests', function(val, oldVal) {
          $timeout.cancel(timeoutTask);
          if (val) {
              timeoutTask = $timeout(function() {
                  $scope.showLoader = true;
              },500);
          }
      });
      
      加价

      <div id="loader" ng-show="showLoader"></div>
      

      您可以使用$timeout service在500毫秒后启动,以检查挂起的请求:

      if ($rootScope.pendingRequests == 0)
      {
           $rootScope.pendingRequestsDebounced = $rootScope.pendingRequests;
      }
      else
      {
           var currentTimeoutHandler = $timeout(function()
           {
              $rootScope.pendingRequestsDebounced = $rootScope.pendingRequests;
              //You can keep checking 500 ms later by creating new timeout call right in here
           },500);
      }
      
      编辑:传递给$timeout的函数只执行一次,在本例中为500毫秒后执行。如果您只想执行该函数一次(看起来是这样),那么上面的代码就足够了。但是,如果要每500毫秒调用一个函数,则需要编写:

      var currentTimeoutHandler = $timeout(checkFn, 500);  
      function checkFn() 
      { 
          $rootScope.pendingRequestsDebounced = $rootScope.pendingRequests; 
          currentTimeoutHandler = $timeout(checkFn, 500);  //Re-execute this function after 500ms
      };
      

      创建一个计时器并将其设置为500毫秒,每当它变为零(或低于零)时,将其重置为500毫秒并检查旋转值


      使用$watch监视值。一旦它变为零,从上面停止计时器并继续。

      您的ajax调用是同步调用还是异步调用?您能否解释一下您的评论的意思,并说明如何再次检查?