【JS】手写防抖

发布时间 2023-09-06 20:39:14作者: zjy4fun

防抖分为立即执行版本非立即执行版本

 

<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>防抖</title>
</head>
 
<body>
 
</body>
<script>
    /**
    * @desc 函数防抖---“立即执行版本” 和 “非立即执行版本” 的组合版本
    * @param func 需要执行的函数
    * @param wait 延迟执行时间(毫秒)
    * @param immediate---true 表立即执行,false 表非立即执行
    **/
    function debounce(func, wait, immediate) {
        let timer;
 
        return function () {
            let context = this;
            let args = arguments;
 
            if (timer) clearTimeout(timer);
 
            if (immediate) {
                var callNow = !timer;
                timer = setTimeout(() => {
                    timer = null;
                }, wait)
                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>