一、前置知识
闭包和防抖知识需要掌握才能看懂
二、函数封装
- //callback(fn)回调函数
- //delay(Number) 延迟执行时间,毫秒
- //isImmediately第一次是否立即执行
- function debounce(callback, delay, isImmediately) {
- //声明变量存储当前定时器
- let timer = null;
- //控制第一次点击时不开启定时器,而是直接运行回调函数
- let i = 1;
- return function (value) {
- //根据isImmediately来判断第一次是否立即执行
- if (isImmediately && i === 1) {
- callback(value)
- i++
- }
- else {
- //判断当前的定时器是否存在,存在就关闭定时器,不存在就重新开启定时器
- if (timer) {
- //存在,清除定时器
- clearTimeout(timer)
- }
- //不存在,开启新定时器
- timer = setTimeout(() => {
- callback(value)
- }, delay)
- }
- }
-
- }
三、完整案例:
- html>
- <html lang="en">
-
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Documenttitle>
- head>
-
- <body>
- <button onclick="fn1()">button>
- <script>
- let name = 'hsq'
- let testDebounce = debounce((name) => {
- console.log(name);
- }, 1000, true)
- function fn1() {
- testDebounce(name);
- }
- //callback(fn)回调函数
- //delay(Number) 延迟执行时间,毫秒
- //isImmediately第一次是否立即执行
- function debounce(callback, delay, isImmediately) {
- //声明变量存储当前定时器
- let timer = null;
- //控制第一次点击时不开启定时器,而是直接运行回调函数
- let i = 1;
- return function (value) {
- //根据isImmediately来判断第一次是否立即执行
- if (isImmediately && i === 1) {
- callback(value)
- i++
- }
- else {
- //判断当前的定时器是否存在,存在就关闭定时器,不存在就重新开启定时器
- if (timer) {
- //存在,清除定时器
- clearTimeout(timer)
- }
- //不存在,开启新定时器
- timer = setTimeout(() => {
- callback(value)
- }, delay)
- }
- }
-
- }
- script>
- body>
-
- html>