Skip to content

Instantly share code, notes, and snippets.

@dlucidone
Last active February 12, 2019 03:29
Show Gist options
  • Save dlucidone/9cac9de8ef5214a371c0b98dc936cdf3 to your computer and use it in GitHub Desktop.
Save dlucidone/9cac9de8ef5214a371c0b98dc936cdf3 to your computer and use it in GitHub Desktop.
Debounce & Throttle
1- Debounce
<html>
<body>
<button id="debounce">
Debounce
</button>
<script>
var button = document.getElementById("debounce");
const debounce = (func, delay) => {
let debounceTimer
return function() {
const context = this
const args = arguments
clearTimeout(debounceTimer)
debounceTimer
= setTimeout(() => func.apply(context, args), delay)
}
}
button.addEventListener('click', debounce(function() {
alert("Hello\nNo matter how many times you" +
"click the debounce button, I get " +
"executed once every 3 seconds!!")
}, 3000));
</script>
</body>
</html>
=======================================================
const debounce = (fn, time) => {
let timeout;
return function() {
const functionCall = () => fn.apply(this, arguments);
clearTimeout(timeout);
timeout = setTimeout(functionCall, time);
}
}
==========================================================
function debounce(callback, delay) {
var timer = null;
return function() {
if (timer) return;
callback.apply(this, arguments);
timer = setTimeout(() => timer = null, delay);
}
}
2- Throttle
function throttle(callback, delay) {
let isThrottled = false, args, context;
function wrapper() {
if (isThrottled) {
args = arguments;
context = this;
return;
}
isThrottled = true;
callback.apply(this, arguments);
setTimeout(() => {
isThrottled = false;
if (args) {
wrapper.apply(context, args);
args = context = null;
}
}, delay);
}
return wrapper;
}
let logger = console.log;
let dlogger = debounce(logger, 5000);
dlogger(1); //log 1
dlogger(2); //ignore
dlogger(3); //ignore
setTimeout(() => dlogger(4), 5000) //log 4
let tlogger = throttle(logger, 5000);
tlogger(1); //log 1
tlogger(2); //ignore
setTimeout(() => tlogger(3), 5000) //log 3
tlogger(4); //last call waits 5 second and then log 4
let ylogger = yours_throttle(logger, 5000);
tlogger(1); //waits 5 second and then log 1
tlogger(2); //ignore
tlogger(3); //ignore
=================================================
const throttle = (func, limit) => {
let lastFunc
let lastRan
return function() {
const context = this
const args = arguments
if (!lastRan) {
func.apply(context, args)
lastRan = Date.now()
} else {
clearTimeout(lastFunc)
lastFunc = setTimeout(function() {
if ((Date.now() - lastRan) >= limit) {
func.apply(context, args)
lastRan = Date.now()
}
}, limit - (Date.now() - lastRan))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment