js防抖跟节流

主要记录于5.18事件,砥砺前行,不忘初心。

App.vue

<template>
  <div id="app_content">
    <Debounce />
    <Throttle />
  </div>
</template>

<script>
import Debounce from './components/Debounce'
import Throttle from './components/Throttle'
export default {
  name: 'App',
  components: {Debounce, Throttle},
  data() {
    return {
    }
  },
  mounted() {
  }
}
</script>

<style>

</style>

防抖(比如说我们一直点击按钮  只有不点击按钮之后1秒才会触发)

<template>
    <div>
       <div> 防抖 </div>
        <div>
            <button @click="testClick">测试防抖</button>
        </div>
    </div>
</template>

<script>
    export default {
        name: "Debounce",
        data() {
            return {
                timeOut: null
            }
        },
        mounted() {
        },
        methods: {
            // 比如说我们一直点击按钮  只有不点击按钮之后1秒才会触发

            // 防抖:任务频繁触发的情况下,只有任务触发的间隔超过指定间隔的时候,任务才会执行
            // 通俗来讲:所谓防抖,就是指触发事件后在 n 秒内函数只能执行一次,如果在 n 秒内又触发了事件,则会重新计算函数执行时间。

            testClick() {
                console.log("---点击事件触发---");
                this.debounce(this.sayDebounce)
            },
            debounce(fn) {
                if (this.timeOut) clearTimeout(this.timeOut);
                this.timeOut = setTimeout(() => {
                    fn()
                }, 1000);
            },
            // 防抖之后触发的函数
            sayDebounce() {
                console.log("防抖成功!");
            }
        }
    }
</script>

<style scoped>

</style>

节流 (比如说我们一直点击按钮  1秒之后会触发一次  然后1秒之后又会触发一次......)

<template>
    <div>
        <div> 节流 </div>
        <div>
            <button @click="testClick">测试节流</button>
        </div>
    </div>
</template>

<script>
    export default {
        name: "Throttle",
        data() {
            return {
                canRun: true
            }
        },
        methods: {
            // 比如说我们一直点击按钮  1秒之后会触发一次  然后1秒之后又会触发一次......

            // 节流:指定时间间隔内只会执行一次任务
            // 通俗来讲:所谓节流,就是指连续触发事件但是在 n 秒中只执行一次函数。 节流会稀释函数的执行频率。

            testClick() {
                console.log("---点击事件触发---");
                this.throttle(this.sayThrottle)
            },
            throttle(fn) {
                if(!this.canRun) return;
                this.canRun = false;
                setTimeout( () => {
                    fn();
                    this.canRun = true;
                }, 1000);
            },
            sayThrottle() {
                console.log("节流成功!")
            }
        }
    }
</script>

<style scoped>

</style>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

An_s

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值