Typescript + Vue实现节流throttle函数

766 阅读1分钟

应用场景: 连续点击按钮时3秒内只触发一次

<template lang="pug">
   .btn(@click="handleClick(text)")
</template>
<script lang="ts" scoped>
   handleClick: any = null;
   created() {
       this.handleClick = this.throttle(this.clickMethod, 3000);
   }
   throttle(fn: any, delay: number) {
       var timer = null;
       var that = this;
       return function() {
           var args = Array.prototype.slice.call(arguments);
            if(!timer) {
                timer = setTimeout(()=> {
                    timer = null;
                }, delay);
                fn.apply(that, args);//避免首次点击时3秒后才会响应
            }
       }     
   }
    clickMethod(text: string) {
        console.log(text);//该text就是handleClick(text)中的参数text
        .../**其他操作*/
    }
</script>