Instantly share code, notes, and snippets.

Embed
What would you like to do?
Debounce function wrapped in an Angular service
<!DOCTYPE html>
<html xmlns:ng="http://angularjs.org" xmlns:svg="http://www.w3.org/2000/svg">
<head>
<meta charset="utf-8" />
<!--
NOTE: Angular has a debounce directive built in as of AngularJS 1.3 in the form
of ng-model-options: https://docs.angularjs.org/api/ng/directive/ngModelOptions
This custom debounce service is intended for events *outside of* Angular such as window resize
-->
<script src="/vendor/angular/angular.js"></script>
<script>
'use strict';
angular.module('utils', [])
.service('Debouncer', function($timeout) {
this.debounce = function(func, wait, immediate) {
var thisTimeoutPromise;
return function() {
var context = this, args = arguments;
var runLater = function() {
thisTimeoutPromise = null;
if (!immediate){
func.apply(context, args);
}
};
var callNow = immediate && !timeout;
$timeout.cancel(thisTimeoutPromise);
thisTimeoutPromise = $timeout(runLater, wait);
if (callNow){
func.apply(context, args);
}
};
}
});
//// usage example in a directive:
var demo = angular.module('demo', ['utils'])
.directive('resizeExample', function($window, Debouncer) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
scope.handleWindowResize = Debouncer.debounce(function() {
scope.width = $window.innerWidth;
scope.height = $window.innerHeight;
}, 200);
scope.handleWindowResize();
return angular.element($window).bind('resize', function() {
scope.handleWindowResize();
return scope.$apply();
});
}
}
});
</script>
</head>
<body ng-app="demo">
<h3>Debounce example</h3>
<div resize-example>
<p>width = {{ width }}, height {{ height }}</p>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment