Skip to content

Commit

Permalink
Merge pull request #236 from cupofjoakim/master
Browse files Browse the repository at this point in the history
Rule for throttle
  • Loading branch information
Corbin Taylor authored Nov 18, 2019
2 parents 96a09a2 + 5df853c commit 5665d8a
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 1 deletion.
32 changes: 31 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@ then Lodash/Underscore is the better option.*
1. [_.bind](#_bind)
1. [_.debounce](#_debounce)
1. [_.partial](#_partial)
1. [_.throttle](#_throttle)

**[Lang](#lang)**

Expand Down Expand Up @@ -1647,7 +1648,7 @@ Create a new function that calls _func_ with _thisArg_ and _args_.
**[⬆ back to top](#quick-links)**
### _.debounce
### _.debounce
Create a new function that calls _func_ with _thisArg_ and _args_.
```js
Expand Down Expand Up @@ -1715,6 +1716,35 @@ Create a new function that calls _func_ with _args_.
**[⬆ back to top](#quick-links)**
### _.throttle
Create a new function that limits calls to _func_ to once every given timeframe.
```js
function throttle(func, timeFrame) {
var lastTime = 0;
return function () {
var now = new Date();
if (now - lastTime >= timeFrame) {
func();
lastTime = now;
}
};
}

// Avoid running the same function twice within the specified timeframe.
jQuery(window).on('resize', throttle(calculateLayout, 150));

```
#### Browser Support for `throttle`
![Chrome][chrome-image] | ![Edge][edge-image] | ![Firefox][firefox-image] | ![IE][ie-image] | ![Opera][opera-image] | ![Safari][safari-image]
:-: | :-: | :-: | :-: | :-: | :-: |
5.0 ✔ | 12.0 ✔ | 3.0 ✔ | 9.0 ✔ | 10.5 ✔ | 4.0 ✔ |
**[⬆ back to top](#quick-links)**
## Lang
### _.gt
Expand Down
4 changes: 4 additions & 0 deletions lib/rules/rules.json
Original file line number Diff line number Diff line change
Expand Up @@ -272,5 +272,9 @@
"flatten": {
"compatible": true,
"alternative": "Array.prototype.reduce((a,b) => a.concat(b), [])"
},
"throttle": {
"compatible": true,
"alternative": "Example of native implementation: https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore#_throttle"
}
}
24 changes: 24 additions & 0 deletions tests/unit/all.js
Original file line number Diff line number Diff line change
Expand Up @@ -729,4 +729,28 @@ describe('code snippet example', () => {
);
});
});

describe('throttle', () => {
function throttle(func, timeFrame) {
var lastTime = 0;
return function () {
var now = new Date();
if (now - lastTime >= timeFrame) {
func();
lastTime = now;
}
};
}

it('throttle is not called more than once within timeframe', () => {
let callCount = 0;
const fn = throttle(() => callCount++, 100);

fn();
fn();
fn();

assert.equal(callCount, 1);
});
})
});

0 comments on commit 5665d8a

Please sign in to comment.