一、基于VUE
/**
* @description: 点击事件防爆点
* @param {type} func:正常点击处理事件,wait:延迟事件
* @return: 防爆点
* @author: me
*/
export function throttle (func, wait) {
let context, args, prevArgs, argsChanged, result;
let previous = 0;
return function () {
let now, remaining;
if (wait) {
now = Date.now();
remaining = wait - (now - previous);
}
context = this;
args = arguments;
argsChanged = JSON.stringify(args) != JSON.stringify(prevArgs);
prevArgs = {...args};
if ((argsChanged || wait) && (remaining <= 0 || remaining > wait)) {
if (wait) {
previous = now;
}
result = func.apply(context, args);
context = args = null;
}
return result;
};
}
import {throttle} from '@/common/common';
created () {
// 点击事件节流
this.throttleInit();
},
methods: {
throttleInit () {
this.remoteMethod = throttle(this.savePic, 300);
this.selectFontCli = throttle(this.selectFont, 300);
},
}
二、基于jQ
<!--
* @Description:
* @Version: 2.0
* @Autor: all
* @Date: 2019-08-26 13:45:18
* @LastEditors : ants
* @LastEditTime : 2020-01-13 14:14:02
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport"
content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no, viewport-fit=cover" />
<title>防爆点</title>
</head>
<body>
<button onclick="warp_test()" >点击2s</button>
<br>
<br>
<br>
<button onclick="warp_test2()" >点击4s</button>
</body>
<script>
/**
* @description: 点击事件防爆点
* @param {type} func:正常点击处理事件,wait:延迟事件
* @return:
* @author: me
*/
const throttle = (func,wait) =>{
let context, args , prevArgs, argsChanged,result;
let previous = 0;
return function (){
let now,remainning;
if(wait){
now = Date.now();
remaining = wait - (now - previous);
}
context = this;
args = arguments;
argsChanged = JSON.stringify(args) != JSON.stringify(prevArgs)
prevArgs = {...args}
if(argsChanged || wait && (remaining <=0 || remaining > wait)){
if(wait){
previous = now ;
}
result = func.apply(context,args);
context = args = null;
}
return result
}
}
function test(){
console.log("防爆2s")
}
function test2(){
console.log("防爆4s")
}
const warp_test = throttle(test,2000)
const warp_test2 = throttle(test2,4000)
</script>
</html>
网友评论