some demos
jsfiddle order: /result,js,html,css/
debounce & throttle
code
debounce
// debounce
function debounce(fn, time = 100, options = {}) {
let args = Array.prototype.slice.call(arguments);
let timeout = null;
let debouncing = false;
let {
leading
} = options;
return function() {
if (leading) {
console.log('x', timeout);
if (!timeout && !debouncing) {
fn.apply(this, args);
debouncing = true;
setTimeout(() => {
debouncing = false;
leading = false;
timeout = setTimeout(() => {
leading = true;
debouncing = false;
timeout = null;
}, time);
}, time);
}
} else {
clearTimeout(timeout);
timeout = setTimeout(() => {
console.log('xxx', debouncing);
debouncing = false;
timeout = null;
fn.apply(this, args);
leading = true;
}, time);
}
}
}
throttle
// throttle
function throttle(fn, freq = 33.33333) {
let args = Array.prototype.slice.call(arguments);
let processing = false;
return function() {
if (!processing) {
processing = true;
setTimeout(() => {
fn.apply(this, args);
processing = false;
}, freq);
}
}
};
评论
滚动到评论区时自动载入。