Open
Description
`<script setup lang='ts'>
/**
- Implement the custom directive
- Make sure the
onClick
method only gets triggered once when clicked many times quickly - And you also need to support the debounce delay time option. e.g
v-debounce-click:ms
*/
/**
- @param fn 需要执行的函数
- @param delay 延迟的时间
- @returns 一个函数,当用户指定的时间后,该函数会被执行。
*/
// function debounce(fn: Function, delay: number): Function {
// let timer:NodeJS.Timeout = null
// return function(...args: any[]) {
// if(timer) clearTimeout(timer)
// timer = setTimeout(() => {
// fn.apply(this, args)
// }, delay)
// }
// }
/**
- @param fn 需要执行的函数
- @param delay 时间节点
- @returns 一个函数,当用户指定的时间间隔中,函数执行频率降低。
*/
function throttle(fn: Function, delay: number): Function {
let lastTime = Date.now()
return function(...args: any[]) {
console.log(1)
const nowTime = Date.now()
if(nowTime - lastTime >= delay) {
fn.apply(this, args)
lastTime = nowTime
}
}
}
const VDebounceClick = {
mounted(el, binding) {
const { arg, value } = binding
el.addEventListener('click', throttle(value, arg))
}
}
function onClick() {
console.log("Only triggered once when clicked many times quickly")
}