js防抖立即执行和非立即执行的理解

it2024-02-20  62

立即执行:即多次触发事件,第一次会立即执行函数,之后在设定wait事件内触犯的事件无效,不会执行。

非立即执行函数: 多次触发事件,只会在最后一次触发事件后等待设定的wait时间结束时执行一次。

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> </body> <script> /** * @desc 函数防抖---“立即执行版本” 和 “非立即执行版本” 的组合版本 * @param func 需要执行的函数 * @param wait 延迟执行时间(毫秒) * @param immediate---true 表立即执行,false 表非立即执行 **/ function debounce(func, wait, immediate) { let timer; return function () { //this指向debounce let context = this; //即参数,func,wait let args = arguments; //如果timer不为null, 清除定时器 if (timer) clearTimeout(timer); //如果是立即执行 if (immediate) { //定义callNow = !timer var callNow = !timer; //定义wait时间后把timer变为null //即在wait时间之后事件才会有效 timer = setTimeout(() => { timer = null; }, wait) //如果callNow为true,即原本timer为null //那么执行func函数 if (callNow) func.apply(context, args) } else { //如果是不立即执行 //那就是每次重新定时 timer = setTimeout(function () { func.apply(context, args) }, wait); } } } function handle() { console.log(Math.random()); } window.addEventListener("mousemove",debounce(handle,1000,true)); // 调用立即执行版本 // window.addEventListener("mousemove", debounce(handle, 1000, false)); // 调用非立即执行版本 </script> </html>

 

最新回复(0)