工作中经常会使用到 防抖节流 例如 微信支付等
/**
* 函数节流
*/
// 二、函数节流
// 定义
// 规定在一个单位时间内,只能触发一次函数,如果这个单位时间内触发多次函数,只有一次生效; 典型的案例就是鼠标不断点击触发,规定在n秒内多次点击只有一次生效。
// 实现原理
// 其原理是用时间戳来判断是否已到回调该执行时间,记录上次执行的时间戳,然后每次触发 scroll 事件执行回调,回调中判断当前时间戳距离上次执行时间戳的间隔是否已经到达 规定时间段,如果是,则执行,并更新上次执行的时间戳,
// 使用场景
export const throttle=(fn,wait)=> {//节流
var prev=Date.now();
return function () {
//因为是vue组件调用的 所以指向vue实例
var context=this;
var args=arguments;
var now=Date.now();
console.log(now-prev>wait)
if(now-prev>wait){
fn.apply(context,args)
prev=Date.now()
}
}
}
// 一、函数防抖
// 定义
// 在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时;典型的案例就是输入搜索:输入结束后n秒才进行搜索请求,n秒内又输入的内容,就重新计时。
// 实现原理
// 函数防抖的基本思想是设置一个定时器,在指定时间间隔内运行代码时清楚上一次的定时器,并设置另一个定时器,知道函数请求停止并超过时间间隔才会执行。
// 使用场景
// 文本框输入搜索(连续输入时避免多次请求接口)
export const debounce=(func, wait)=>{//防抖
// wait:500ms;func:被频繁触发的事件
let timeout;
return function () {
let context = this;
let args = arguments;
let later = () => {
timeout = null;
func.apply(context, args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
}
}
在vue中使用
<template>
<div class="home">
<!-- <img alt="Vue logo" src="../assets/logo.png"> -->
<!-- <HelloWorld msg="Welcome to Your Vue.js App"/> -->
<!-- <showBox></showBox> -->
<div class="showbox" @click='wechatPay'>
<span>节流函数</span>
</div>
<div class="debounceinput">
<input type="text" class="inputtext" placeholder="请输入文字" @keyup="serchkey" v-model="keyword">
</div>
</div>
</template>
<script>
// @ is an alias to /src
import HelloWorld from '@/components/HelloWorld.vue'
import {throttle,debounce} from '@/utils/common.js'
export default {
name: 'home',
data(){
return {
keyword:''
}
},
components: {
HelloWorld,
// showBox
},
methods:{
//用户点击支付 间隔 1.5秒 触发 微信支付函数
wechatPay:throttle(function(e){
this.wxpay()
},1500),
//微信支付
wxpay(){
console.log('微信支付开始了')
},
//用户输入
serchkey:debounce(function(e){
this.searchkey()
},1000),
//搜索接口
searchkey(){
console.log('搜索关键字'+this.keyword)
}
},
mounted(){
}
}
</script>
<style scoped lang='scss'>
.home{
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
}
.showbox{
margin-top: 30px;
width: 90%;
height:100px;
background-color: rgb(135, 162, 235);
display: flex;
justify-content: center;
border-radius: 130px;
span{
line-height: 100px;
color: #fff;
}
}
.inputtext{
width: 100%;
}
.debounceinput{
margin-top: 30px;
}
</style>