Last active
April 25, 2017 18:16
-
-
Save earlonrails/b7b2863f10e755bf9870c651c3d9ccc1 to your computer and use it in GitHub Desktop.
throttle a function call in javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
"use strict" | |
function throttle(fn, limitInMs) { | |
var count = 0; | |
return function () { | |
var context = this, args = arguments; | |
console.log("waiting: ", limitInMs * count, "ms") | |
setTimeout(function () { | |
fn.apply(context, args) | |
count -= 1; | |
}, limitInMs * count) | |
count += 1; | |
} | |
} | |
// var throttled = throttle(function(b) { console.log(b) }, 5000) | |
// throttled("doesnt wait") | |
// throttled("waits 5s") | |
// throttled("waits 10s") | |
// setTimeout(function(){ | |
// throttled("boo") | |
// }, 2000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment