0

I'm working with angular.

I have a problem with a $timeout function. it is initiate on ng-mousedown so if I clic 2 time, it set 2 timer. That I want to avoid. How Can I delete previous timer to keep only the last one? Here the code:

      $scope.stopRefresh = function() { //ng-mousedown
      $interval.cancel(autoRefresh);
      restartRefresh = $timeout(function(){
      startRefresh();
    },30000);
    };
3
  • use cancel() before setting the timeout Commented Nov 15, 2015 at 1:33
  • If I put it before setting it it return undefine Commented Nov 15, 2015 at 2:16
  • The code is not clear. Why are you doing $interval.cancel(autoRefresh)? Commented Nov 15, 2015 at 2:43

1 Answer 1

2

This code should work:

$scope.stopRefresh = function() { //ng-mousedown
    $interval.cancel(autoRefresh); //I am not clear with the purpose of this line.

    if(restartRefresh){
        $timeout.cancel(restartRefresh);
    }
    restartRefresh = $timeout(function(){
        startRefresh();
    },30000);
};
Sign up to request clarification or add additional context in comments.

5 Comments

have the same problem. Maybe is a better way. i'll try to explain what I want to do. I some Input type number and text input that contain data update on the $interval autoRefresh() every 5 sec. but when I try to clic on it, I have not time to finish my change before the next refresh and change are lost. so I want to froze the interval for 30 sec on ng-mousedown and reset it if I clic OK.
I think you should use focus listener for this. When the input gets the focus, you don't want to refresh. Once the user makes change and the focus is out of the input, then you can restart the timer. This is a better when compared to postponing the refresh for 30 seconds. Because, if the user stays in the input field for more than 30 seconds and makes some change, again it will be lost. Now, it is better to include this logic in a separate directive as it involves handling focus in and focus out.
@ Ganesh Kumar. Thanks that's worked with ng-focus and ng-blur.
One more question... Is there an other way that the data is not refreshing during focus than cancel the interval of all data inputs? For archive, here all my code: Arduino home automation
You are having single $interval on which all inputs are dependent on. I think, you should create a directive for input which encapsulates the $interval service and the start and stop functionalities. Then you can use the directive in multiple places.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.