Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add throttle service #5

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
20 changes: 20 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# EditorConfig helps developers define and maintain consistent
# coding styles between different editors and IDEs
# editorconfig.org

root = true

[*]

# Change these settings to your own preference
indent_style = space
indent_size = 2

# We recommend you to keep these unchanged
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.md]
trim_trailing_whitespace = false
44 changes: 42 additions & 2 deletions Gruntfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,20 @@
module.exports = function (grunt) {
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-release');
grunt.loadNpmTasks('grunt-karma');

grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
karma: {
options: {
configFile: 'karma.conf.js'
},
ci: {
singleRun: true,
preprocessors: {'*.js': 'coverage'},
preprocessors: {'src/*.js': 'coverage'},
reporters: ['progress', 'coverage'],
coverageReporter: {dir : 'coverage/', type: 'lcov'}
},
Expand All @@ -29,12 +32,30 @@ module.exports = function (grunt) {
server: {
}
},
jshint: {
src: {
options: {
jshintrc: '.jshintrc'
},
files: {
src: ['src/*.js', 'Gruntfile.js']
}
},
test: {
options: {
jshintrc: 'test/.jshintrc'
},
files: {
src: ['test/*.js']
}
}
},
watch: {
options: {
livereload: true
},
tests: {
files: ['*.js', 'test/**/*.js', '{demo,css,images}/*.*'],
files: ['src/*.js', 'test/**/*.js', '{demo,css,images}/*.*'],
tasks: ['karma:dev:run']
}
},
Expand All @@ -43,9 +64,28 @@ module.exports = function (grunt) {
file: 'bower.json',
npm: false
}
},
uglify: {
dist: {
options: {
banner: ['/*',
' * <%= pkg.name %>',
' * <%= pkg.homepage %>',
' *',
' * @version: <%= pkg.version %>',
' * @license: <%= pkg.license %>',
' */\n'
].join('\n')
},
files: {
'dist/angular-debounce.min.js': ['src/angular-debounce.js']
}
}
}
});

grunt.registerTask('default', ['jshint', 'karma:ci', 'uglify']);

//run tests only once (continuous integration mode)
grunt.registerTask('test', ['karma:ci']);

Expand Down
26 changes: 22 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,11 @@ Angular Debounce [![Build Status](https://travis-ci.org/shahata/angular-debounce

## What it does

1. Service - Creates and returns a new debounced version of the passed function which will postpone its execution until after **wait** milliseconds have elapsed since the last time it was invoked. Useful for implementing behavior that should only happen *after* the input has stopped arriving. For example: recalculating a layout after the window has stopped being resized.
1. Debounce Service - Creates and returns a new debounced version of the passed function which will postpone its execution until after **wait** milliseconds have elapsed since the last time it was invoked. Useful for implementing behavior that should only happen *after* the input has stopped arriving. For example: recalculating a layout after the window has stopped being resized.

2. Directive - Can be added to any element with an ng-model attribute and postpone model updates by user input until after **wait** milliseconds have elapsed since the last user input. Useful for watchers that should only be invoked *after* the input has stopped arriving. For example: rendering a preview of a Markdown comment.
2. Throttle Service - Creates and returns a new throttled version of the passed function that when called repetitively, executes the original function (in the same context and with all arguments passed through) no more than once every delay milliseconds.

3. Directive - Can be added to any element with an ng-model attribute and postpone model updates by user input until after **wait** milliseconds have elapsed since the last user input. Useful for watchers that should only be invoked *after* the input has stopped arriving. For example: rendering a preview of a Markdown comment.

## Installation

Expand All @@ -25,10 +26,10 @@ Include script tag in your html document.
Add a dependency to your application module.

```javascript
angular.module('myApp', ['debounce']);
angular.module('myApp', ['debounce', 'throttle']);
```

## Service Usage
## Debounce Service Usage

`debounce(func, wait, [immediate])`

Expand All @@ -46,6 +47,23 @@ A debounced version of the passed function. Any arguments passed to this functio

The returned function also has a `cancel()` method which can be used in case you what to reset the current debounce state. This will prevent the function from being triggered even after **wait** miliseconds have passed from last input. In case **immediate** is `true`, this means that the next user input will trigger the debounce.

## Throttle Service Usage

`throttle(func, wait)`

### Arguments

|Param|Type|Details|
|---|---|
|func|function|The function we want to **throttle**|
|wait|number|Number of miliseconds to **wait** before invoking the throttled function|

### Returns

A throttled version of the passed function. Any arguments passed to this function will be also passed to the passed function in case this invocation will trigger the function.

The returned function also has a `cancel()` method which can be used in case you what to reset the current throttle state. This will prevent the function from being triggered even after **wait** miliseconds have passed from last input.

## Directive Usage

```html
Expand Down
8 changes: 8 additions & 0 deletions dist/angular-debounce.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions karma.conf.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ module.exports = function (config) {
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/es5-shim/es5-shim.js',
'angular-debounce.js',
'test/**/*.js'
'src/angular-debounce.js',
'test/*.js'
],

// list of files / patterns to exclude
Expand Down
24 changes: 11 additions & 13 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,21 +19,19 @@
"devDependencies": {
"grunt": "~0.4.2",
"grunt-release": "~0.6.0",
"karma-script-launcher": "~0.1.0",
"karma-chrome-launcher": "~0.1.2",
"karma-firefox-launcher": "~0.1.3",
"karma-html2js-preprocessor": "~0.1.0",
"karma-jasmine": "~0.1.5",
"karma-coffee-preprocessor": "~0.1.2",
"requirejs": "~2.1.10",
"karma-requirejs": "~0.2.1",
"karma-phantomjs-launcher": "~0.1.1",
"karma": "~0.10.9",
"grunt-karma": "~0.6.2",
"karma-script-launcher": "^0.1.0",
"karma-chrome-launcher": "^0.1.3",
"karma-firefox-launcher": "^0.1.3",
"karma-phantomjs-launcher": "^0.1.4",
"karma-jasmine": "^0.2.2",
"karma-coverage": "^0.2.1",
"karma": "^0.12.16",
"grunt-karma": "~0.8.3",
"karma-growl-reporter": "~0.1.1",
"grunt-contrib-watch": "~0.5.3",
"grunt-contrib-connect": "~0.6.0",
"karma-coverage": "~0.1.4",
"coveralls": "~2.6.1"
"coveralls": "~2.6.1",
"grunt-contrib-uglify": "^0.4.0",
"grunt-contrib-jshint": "^0.10.0"
}
}
42 changes: 42 additions & 0 deletions angular-debounce.js → src/angular-debounce.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,48 @@ angular.module('debounce', [])
return debounce;
};
}])
.service('throttle', ['$timeout', 'debounce', function($timeout, debounce) {
return function(func, wait) {
var context, args, timeout, throttling, more, result;

var whenDone = debounce(function() {
more = throttling = false;
}, wait);

function throttle() {
/* jshint validthis:true */
context = this;
args = arguments;

var later = function() {
timeout = null;
if (more) {
func.apply(context, args);
}

whenDone();
};
if (!timeout) {
timeout = $timeout(later, wait);
}
if (throttling) {
more = true;
} else {
result = func.apply(context, args);
}
whenDone();
throttling = true;

return result;
}
throttle.cancel = function () {
$timeout.cancel(timeout);
timeout = null;
};

return throttle;
};
}])
.directive('debounce', ['debounce', function (debounce) {
return {
require: 'ngModel',
Expand Down
72 changes: 68 additions & 4 deletions test/angular-debounce.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ describe('unit testing angular debounce service', function () {
debounced(2);
debounced(3);
$timeout.flush(100);
expect(spy.calls.length).toEqual(1);
expect(spy.calls.count()).toEqual(1);
expect(spy).toHaveBeenCalledWith(3);
});

Expand All @@ -54,7 +54,7 @@ describe('unit testing angular debounce service', function () {
});

it('should return the value from the last debounce', function () {
var spy = jasmine.createSpy('debounceFunc').andCallFake(angular.identity);
var spy = jasmine.createSpy('debounceFunc').and.callFake(angular.identity);
var debounced = debounce(spy, 100);
expect(debounced(1)).toEqual(undefined);
$timeout.flush(100);
Expand All @@ -69,7 +69,7 @@ describe('unit testing angular debounce service', function () {
debounced(3);
expect(spy).toHaveBeenCalledWith(1);
$timeout.flush(100);
expect(spy.calls.length).toEqual(1);
expect(spy.calls.count()).toEqual(1);
debounced(2);
expect(spy).toHaveBeenCalledWith(2);
});
Expand Down Expand Up @@ -103,7 +103,7 @@ describe('unit testing angular debounce directive', function () {
defer = null;
module(function ($provide) {
$provide.service('debounce', function ($q) {
debounce = jasmine.createSpy('debounce').andCallFake(function (func) {
debounce = jasmine.createSpy('debounce').and.callFake(function (func) {
/* jshint validthis:true */
function debounced() {
var args = arguments;
Expand Down Expand Up @@ -189,5 +189,69 @@ describe('unit testing angular debounce directive', function () {
element = $compile('<input type="text" ng-model="blah" debounce="100" immediate="true"></input>')($rootScope);
expect(debounce).toHaveBeenCalledWith(jasmine.any(Function), 100, true);
});
});

describe('Unit test throttle service', function() {
var throttle, $timeout;

beforeEach(module('debounce'));

beforeEach(function () {
inject(function (_throttle_, _$timeout_) {
throttle = _throttle_;
$timeout = _$timeout_;
});
});

it('should invoke callback at specified delay', function () {
var spy = jasmine.createSpy('throttleFunc');
expect(spy).not.toHaveBeenCalled();
var t = throttle(spy, 200);

t();

expect(spy.calls.count()).toBe(1);

t();
t();
t();
t();

$timeout.flush(100);
expect(spy.calls.count()).toBe(1);

$timeout.flush(120);
expect(spy.calls.count()).toBe(2);
$timeout.flush();
});

it('should be able to create multiple unrelated debouncers', function () {
var spy = jasmine.createSpy('throttleFunc');
var spy2 = jasmine.createSpy('throttleFunc2');
throttle(spy, 100)(1);
throttle(spy2, 100)(2);
$timeout.flush(100);
expect(spy).toHaveBeenCalledWith(1);
expect(spy2).toHaveBeenCalledWith(2);
});

it('should return the value from the last throttle', function () {
var spy = jasmine.createSpy('throttleFunc').and.callFake(angular.identity);
var throttled = throttle(spy, 100);
expect(throttled(1)).toEqual(1);
$timeout.flush(100);
expect(throttled(2)).toEqual(1);
});

it('should support canceling of throttle, returning triggers to default state', function () {
var spy = jasmine.createSpy('throttleFunc');
var t = throttle(spy, 100);
t();
expect(spy.calls.count()).toBe(1);
t.cancel();
expect(spy.calls.count()).toBe(1);
$timeout.flush(100);
expect(spy.calls.count()).toBe(1);
});

});