微信小程序开发,如果防止按钮重复点击,请列出两种实现方式的代码
时间: 2024-05-12 20:18:39 浏览: 5
可以使用debounce和throttle两种方式来防止按钮重复点击:
1. debounce方式:
```
function debounce(fn, delay) {
let timer = null;
return function () {
let context = this;
let args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
fn.apply(context, args);
}, delay);
}
}
//在需要绑定事件的元素上添加事件监听,当事件被触发时调用debounce进行函数防抖
element.addEventListener('click', debounce(function() {
//处理点击事件
}, 1000));
```
2. throttle方式:
```
function throttle(fn, delay) {
let timeout = null;
return function () {
let context = this;
let args = arguments;
if (!timeout) {
timeout = setTimeout(function () {
fn.apply(context, args);
timeout = null;
}, delay);
}
}
}
//在需要绑定事件的元素上添加事件监听,当事件被触发时调用throttle进行函数节流
element.addEventListener('click', throttle(function() {
//处理点击事件
}, 1000));
```