如何使用 js 实现一个 debounce 函数
- 原理
防抖: 是指在指定的单位时间内,如果重复触发了相同的事件,则取消上一次的事件,重新开始计时!
- 实现方式
"use strict";
/**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2020-10-01
* @modified
*
* @description 防抖 & debounce
* @difficulty Easy Medium Hard
* @complexity O(n)
* @augments
* @example
* @link
* @solutions
*
* @best_solutions
*
*/
const log = console.log;
// 防抖: 是指在指定的单位时间内,如果重复触发了相同的事件,则取消上一次的事件,重新开始计时!
function debounce(callback, timer = 1000) {
let id = null;
return function() {
clearTimeout(id);
id = setTimeout(() => {
callback();
}, timer);
}
}
const cb = () => log(`callback function!`)
const test = debounce(cb, 3000);
log(`test`, test);
test();
setTimeout(() => {
log(`test2`);
test();
}, 1000);
setTimeout(() => {
log(`test3`);
test();
}, 2000);
/*
$ node debounce.js
test [Function]
test2
test3
callback function!
*/
this & arguments
"use strict";
/**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2020-10-01
* @modified
*
* @description 防抖 & debounce
* @difficulty Easy Medium Hard
* @complexity O(n)
* @augments
* @example
* @link
* @solutions
*
* @best_solutions
*
*/
const log = console.log;
// 防抖: 是指在指定的单位时间内,如果重复触发了相同的事件,则取消上一次的事件,重新开始计时!
function debounce(callback, timer = 1000) {
let id = null;
return function() {
// const args = [...arguments];
const args = arguments;
const that = this;
// function (this, arguments)
clearTimeout(id);
id = setTimeout(function () {
log(`that`, that)
log(`this`, this)
log(`args`, args)
callback.call(that, [...args]);
}, timer);
// Arrow Function (this)
// id = setTimeout(() => {
// callback();
// }, timer);
}
}
// const cb = () => log(`callback function!`);
const cb = (args) => log(`callback function!`, args);
const test = debounce(cb, 3000);
log(`test`, test);
test(`args = arguments`, 1);
setTimeout(() => {
log(`test2`);
test(`args = arguments`, 2);
}, 1000);
setTimeout(() => {
log(`test3`);
test(`args = arguments`, 3);
}, 2000);
/*
$ node debounce.js
test [Function]
test2
test3
callback function!
*/
/*
$ node debounce.js
test [Function]
test2
test3
that undefined
this Timeout {
_idleTimeout: 3000,
_idlePrev: null,
_idleNext: null,
_idleStart: 2044,
_onTimeout: [Function],
_timerArgs: undefined,
_repeat: null,
_destroyed: false,
[Symbol(refed)]: true,
[Symbol(asyncId)]: 11,
[Symbol(triggerId)]: 7
}
args [Arguments] { '0': 'args = arguments', '1': 3 }
callback function! [ 'args = arguments', 3 ]
*/
- 总结
refs
https://www.cnblogs.com/xgqfrms/p/11886342.html
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function
©xgqfrms 2012-2020
www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!