【问题标题】:Call and stop a rest service with an interval of time每隔一段时间调用和停止一个休息服务
【发布时间】:2017-07-06 19:07:04
【问题描述】:

我需要每隔 x 间隔秒 (3000 毫秒) 进行一次休息调用以查询 Web 服务的状态,直到我得到想要的结果或直到 12 次(例如)或当我收到预期的状态时:

function myFunction() {
    var i=0;
    var _onSuccess = function(response) {
        if (response.status=== 'READY' || i >= 12) {
            clearInterval(x);
            if(response.status !== 'READY') {
                $location.path('/errorView');
            }
        }
    }
    var x = setInterval(function () {
       $rest.getSomething(_onSuccess)
    }, 3000);
}

我有另一个函数调用 myFunction 并超时,因为如果我在 32 秒后没有收到预期的结果,我想取消停止休息调用并转到错误视图。

function myFunction2() {
    myFunction();
    $timeout(function () {
        $location.path('/routeWhenStatusReady');
    }, 32000); 
}

有什么办法可以改善吗?例如,如果 Ready 状态在 16 秒内正常,我想完成超时 myFunction2,而不是等待 32 秒...

谢谢!

【问题讨论】:

    标签: javascript angularjs


    【解决方案1】:

    您可以在变量中设置 $timeout:

    var myTimeout = $timeout

    并完成:

    $timeout.cancel(myTimeout);

    【讨论】:

      【解决方案2】:

      $timeout 计时器存储在myFunction 可以访问的全局范围内。并在达到您想要的结果时取消计时器。

      var timer=null;
      
      function myFunction(){
      var i=0;
          var _onSuccess = function(response){
              if (response.status=== 'READY' || i >= 12) {
                  clearInterval(x);
                  if(timer){
                    $timeout.cancel(timer);
                  }
                  if(response.status !== 'READY'){
                      $location.path('/errorView');
                  }
              }
          }
      var x = setInterval(function () {
                  $rest.getSomething(_onSuccess)
              }, 3000);
      }
      
      function myFunction2(){
            myFunction();
            timer = $timeout(function () {
              $location.path('/routeWhenStatusReady');
            }, 32000); 
         }
      

      【讨论】:

        【解决方案3】:

        第 1 步:

        将 $interval 分配给变量

         var timeHandler = $interval(() => {
                        // your code
         }, 1000) };
        

        第 2 步:

        并通过在间隔取消函数

        中传递变量来取消它
        $interval.cancel(timeHandler);
        

        参考:here

        【讨论】:

          猜你喜欢
          • 2019-04-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-04-02
          • 1970-01-01
          • 2015-05-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多