Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Debounce function wrapped in an Angular service
<!DOCTYPE html>
<html xmlns:ng="" xmlns:svg="">
<meta charset="utf-8" />
NOTE: Angular has a debounce directive built in as of AngularJS 1.3 in the form
of ng-model-options:
This custom debounce service is intended for events *outside of* Angular such as window resize
<script src="/vendor/angular/angular.js"></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;
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);
return angular.element($window).bind('resize', function() {
return scope.$apply();
<body ng-app="demo">
<h3>Debounce example</h3>
<div resize-example>
<p>width = {{ width }}, height {{ height }}</p>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.