Search code examples
javascriptangularjscounttimeout

Angular one: javascript timeout function


I'm trying to call a function based on an input value. The scenario will: if nobody will add something in that input for 10 seconds (so the value will be null), make that input disabled. I would like to use ng-change or something similar from angular methods instead of any "keyboard key" conditions.

Now the first think to do is to set timer to 0 when the button is clicked and counting to 10.

angular.module('myApp', [])
  .controller('myCtrl', ['$scope', function($scope) {
  $scope.count = 10;
  $scope.inpValue = '';

  function myFunction() {
    setTimeout(function() {
      if ($scope.inpValue.length === 0 && $scope.count >= 10) {
        alert("Execute function when if is true");
      }
    }, 1000);
  };
  myFunction();

}]);

JSFIDDLE:


Solution

  • Though the problem statement is ambiguous, this is probably what you require.

    • If no value is entered in the input box, it will disable in 10 seconds.
    • If the value is changed, the timer resets to default and re runs.
    • Close on 10 button also resets the timer but button gets disabled once clicked. It only gets enabled when the value of the input box changes.

    angular.module('myApp', []).controller('myCtrl', ['$scope', '$timeout', function($scope, $timeout) {
      $scope.count = 1;
      $scope.inpValue = "";
      $scope.disableInput = false;
      $scope.disableBtn = false;
    
      $scope.checkToDisable = function() {
        console.log($scope.count);
    
        $scope.customTimeout = $timeout(function() {
          if ($scope.inpValue.length === 0 && $scope.count == 10) {
            $scope.count = 0;
            $scope.disableInput = true;
            $scope.disableBtn = true;
            $timeout.cancel($scope.customTimeout);
          } else {
            $scope.count++;
            $scope.checkToDisable();
            if ($scope.count > 10) {
              $timeout.cancel($scope.customTimeout);
            }
          }
        }, 1000);
      };
    
      $scope.resetTimer = function() {
        $scope.count = 1;
        $timeout.cancel($scope.customTimeout);
        $scope.checkToDisable();
      };
    
      $scope.checkToDisable();
    
    }]);
    button {
      border: none;
      padding: 5px 2px;
      border-radius: 4px;
      box-shadow: inset 1px 1px 4px red;
    }
    
    button:active {
      background: orange;
      border: none;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
    
    <body ng-app="myApp">
      <div ng-controller="myCtrl">
        <input type='text' ng-model="inpValue" ng-change="resetTimer(); disableBtn = false;" ng-disabled="disableInput" />
        <button ng-click="resetTimer(); disableBtn = true;" ng-disabled="disableBtn">Close when it reaches 10</button>
      </div>
    </body>