npm i debounceer
Usage in vue components
import {debounce} from 'debounceer';
export default {
setup(){
// call the debounce function
const handler= debounce(function{
alert('do sth')
})
return {
handler
}
},
methods:{
// call the debounce function
handler2:debounce(
function(){
alert('do sth')
}
)
}
}
export function debounce(fn, timeout = 200) {
// Save the timer id.
var timer;
return function (...args) {
// Save the this object
const that = this;
// If the timer is exist
timer > 0 && clearTimeout(timer)
// Restart the timer
timer = setTimeout(() => {
// Call the function some seconds later
fn && fn.apply(that, args);
}, timeout);
}
}
import {throttle} from 'debounceer';
export default {
setup(){
// call the throttle function
const handler=throttle(function(){
alert('do sth')
})
return {
handler
}
},
methods:{
// call the target function some seconds later
handler2:throttle(
function(){
alert('do sth')
}
)
}
}
// Throttle Function
// fn: The function will be called.
// time: The delay time.
export function throttle(fn, timeout = 150) {
// Save the timer id
var timer;
return function (...args) {
// If the timer is exist
if (!timer) {
// Save the this object
var that = this;
// Start the timer
timer = setTimeout(() => {
//Call the function some seconds later
fn && fn(that, args);
}, timeout);
}
}
}