Last active
July 25, 2018 00:36
-
-
Save mglnb/31ab10cea6062fd700bcb825004b5230 to your computer and use it in GitHub Desktop.
Throttle
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
/** | |
* @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