Skip to content

Instantly share code, notes, and snippets.

@mglnb
Last active July 25, 2018 00:36
Show Gist options
  • Save mglnb/31ab10cea6062fd700bcb825004b5230 to your computer and use it in GitHub Desktop.
Save mglnb/31ab10cea6062fd700bcb825004b5230 to your computer and use it in GitHub Desktop.
Throttle
/**
* @param {Function} fn - Função a ser executada
* @param {Number} time - Tempo em milisegundos
*/
function throttle (fn, time) {
var ctx
var args
var result
var timeout = null
var previous = 0
var later = function () {
previous = 0
timeout = null
result = fn.apply(ctx, args)
ctx = null
args = null
}
return function() {
var now = Date.now()
if(!previous) {
previous = now
}
var remaining = time - (now - previous)
var context = this
var args = arguments
if(remaining <= 0) {
clearTimeout(timeout)
timeout = null
previous = now
result = fn.apply(ctx, args)
context = null
args = null
} else if(!timeout) {
timeout = setTimeout(later, remaining)
}
return result
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment