Implement a delay on $scope.$watch

前端 未结 5 1609
醉话见心
醉话见心 2021-02-07 03:33

I was wondering whether or not it is possible to implement a slight delay on $scope.$watch. I have the following which queries the server, so I\'d like to implement a slight del

5条回答
  •  迷失自我
    2021-02-07 04:00

    Normally i'd say use angular's $timeout for this delay but you cant clear this timeout yet.

    //EDIT:you can.

    Set a timeout and clear it, if this watcher gets triggered fast enought.

    Like this:

    var timeoutCode;
    var delayInMs = 2000;
    $scope.$watch("query", function(query) {
     clearTimeout(timeoutCode);  //does nothing, if timeout alrdy done
     timeoutCode = setTimeout(function(){   //Set timeout
         $scope.loading = true;
         returnFactory.query(query).then(function(returns) {
           $scope.returns = returns;
           $scope.loading = false;
         });
     },delayInMs);
    });
    

    http://jsfiddle.net/4FuyY/

    UPDATE Thanks to stewie this can be achieved with angular's $timeout.

        var timeoutPromise;
        var delayInMs = 2000;
        $scope.$watch("query", function(query) {
         $timeout.cancel(timeoutPromise);  //does nothing, if timeout alrdy done
         timeoutPromise = $timeout(function(){   //Set timeout
             $scope.loading = true;
             returnFactory.query(query).then(function (returns) {
               $scope.returns = returns;
               $scope.loading = false;
             });
         },delayInMs);
        });
    

提交回复
热议问题