《前端面试题》- JS基础 - 防抖和节流

在界面触发点击,滚动,输入校验等事件时,如果对事件的触发频率不加以限制,会给浏览器增加负担,且对用户不友好。防抖和节流就是针对类似情况的解决方案。

防抖

防抖(debounce):当连续触发事件时,一定时间段内没有再触发事件,事件处理函数才会执行一次,如果设定的时间到来之前,又一次触发了事件,就重新开始延时。

示例:

<!DOCTYPE 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>Document</title>
</head>
<body>
    <div>点击<span class="count">0</span>次</div>
    <button class="button">button</button>
    <script>
        let count = 0;
        function debounce(fn, await) {
            let timer = null;
            return function(...args) {
                if(timer) clearTimeout(timer);
                timer = setTimeout(() => fn.apply(this, args), await);
            }
        }

        function calCount() {
            const ele = document.getElementsByClassName('count')[0];
            count++;
            ele.innerHTML = count;
        }

        const btn = document.getElementsByClassName('button')[0];
        btn.addEventListener('click', debounce(calCount, 1000));
    </script>
</body>
</html>

节流

节流(throttle):当持续触发事件时,保证一定时间段内只调用一次事件处理函数。

示例:

<!DOCTYPE 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>Document</title>
</head>
<body>
    <div>点击<span class="count">0</span>次</div>
    <button class="button">button</button>
    <script>
        let count = 0;
        function throttle(fn, await) {
            let preTime = Date.now();
            return function(...args) {
                let now = Date.now();
                if(now - preTime >= await) {
                    fn.apply(this, args);
                    preTime = Date.now();
                }
            }
        }

        function calCount() {
            const ele = document.getElementsByClassName('count')[0];
            count++;
            ele.innerHTML = count;
        }

        const btn = document.getElementsByClassName('button')[0];
        btn.addEventListener('click', throttle(calCount, 1000));
    </script>
</body>
</html>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 2.什么是函数柯里化? 答:是把接受多个参数的函数变换成接受一个单一参数(最初函数的第一个参数)的函数,并且返回接...
    Rain_Wuu阅读 2,294评论 1 8
  • 在进行窗口的resize、scroll,输入框内容校验等操作时,如果事件处理函数调用的频率无限制,会加重浏览器的负...
    iqing2012阅读 808评论 0 1
  • 在上周的开发中,又遇到点击保存多次请求数据重复的问题,所以下来学习了一下js的防抖和节流。通过学习了解到,在进行窗...
    any_5637阅读 400评论 0 2
  • 在进行窗口的resize、scroll,输入框内容校验等操作时,如果事件处理函数调用的频率无限制,会加重浏览器的负...
    为光pig阅读 342评论 0 3
  • 什么事单线程? 主线程只有一个线程,同一时刻只能执行单个任务 为什么选择单线程? JavaScript的主要用途是...
    祝家庄打烊阅读 681评论 0 2