Skip to content

Instantly share code, notes, and snippets.

@earlonrails
Last active April 25, 2017 18:16
Show Gist options
  • Save earlonrails/b7b2863f10e755bf9870c651c3d9ccc1 to your computer and use it in GitHub Desktop.
Save earlonrails/b7b2863f10e755bf9870c651c3d9ccc1 to your computer and use it in GitHub Desktop.
throttle a function call in javascript
#!/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