Search code examples
angularjstimerautosave

How to count an amount of time from the last of a particular event, in AngularJS app


In my Angular app, I want to autosave the changes a user makes.

My strategy for doing this is that I want to autosave 20 seconds after the user stops making changes. That is, if he is actively editing, I want the timer to keep resetting itself until the final keystroke, when it is allowed to run its full 20 second course and trigger the autosave.

How can I maintain a clock in Angular that can be reset regularly and used to trigger a function?


Solution

  • have a look at $timeout in angular, you could call this from a function that is attached to each input box via ng-change. Cancel the promise and re-create it everytime ng-change is hit.

    HTML:

      <body ng-controller="MainCtrl">
    
        <input type=text ng-model="theValue" ng-change="QueueAutoSave()" />
    
      </body>
    

    SCRIPT:

    var app = angular.module('plunker', []);
    
    app.controller('MainCtrl', function($scope,$timeout) {
      $scope.theValue = 'World';
    
      var autoSavePromise;
    
      $scope.QueueAutoSave=function(){
        $timeout.cancel(autoSavePromise);
        autoSavePromise=$timeout(function(){
          alert("saved!");
        }, 20000);
      }
    });
    

    working example: plunk