JavaScript Throttle 函数实现防抖功能及自动执行原因解析

这段代码实现了一个简单的 throttle 函数,用于限制函数的执行频率,防止频繁触发导致性能问题。

let Input = document.querySelector('div');
Input.addEventListener('focus', throttle(demo, 2000))
function throttle(fn, time) {
    let timer = null;
    alert(1)
    return () => {
        if (!timer) {
            timer = setTimeout(() => {
                timer = null;
            }, 2000)
        }
    }
}
function demo() {
    console.log('发起请求')
}

自动执行原因解析

这段代码会在页面加载时自动执行,主要是因为以下两点:

  1. querySelector 方法: querySelector('div') 会在页面加载时立即查找并返回第一个匹配的 <div> 元素。如果页面中存在 <div> 元素,则 Input 变量会立即被赋值,代码块随之执行。
  2. alert 函数: throttle 函数中包含 alert(1),该函数会弹出提示框,也意味着代码被执行。

如何避免自动执行

为了避免代码在页面加载时自动执行,我们可以将代码块放在一个事件监听函数中,比如:

window.addEventListener('load', () => {
    let Input = document.querySelector('div');
    Input.addEventListener('focus', throttle(demo, 2000))
    function throttle(fn, time) {
        let timer = null;
        return () => {
            if (!timer) {
                timer = setTimeout(() => {
                    timer = null;
                }, 2000)
            }
        }
    }
    function demo() {
        console.log('发起请求')
    }
});

这段代码将代码块放在了 window.onload 事件监听函数中,确保代码在页面完全加载完毕后再执行,避免了自动执行问题。

小结

本文详细解释了 JavaScript 中 throttle 函数的实现原理以及代码自动执行的原因,并提供了解决方法。希望本文对读者有所帮助。

JavaScript Throttle 函数实现防抖功能及自动执行原因解析

原文地址: https://www.cveoy.top/t/topic/m2LZ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录