Skip to content

Instantly share code, notes, and snippets.

@muedsa
Created January 24, 2022 05:11
Show Gist options
  • Save muedsa/217bb8f0bf556e00a67952c69eda00dc to your computer and use it in GitHub Desktop.
Save muedsa/217bb8f0bf556e00a67952c69eda00dc to your computer and use it in GitHub Desktop.
debounc throttle by Proxy
<template>
<div id="app">
<test-component></test-component>
<test-component></test-component>
</div>
</template>
import TestComponent from 'test-component'
<script>
export default {
components: {
TestComponent
}
};
</script>
const createDebounce = function (fn, delay) {
let runMap = new Map();
const handler = {
apply: function (target, context, argumentsList) {
let timerId = runMap.get(context);
if (timerId) {
clearTimeout(timerId);
}
timerId = setTimeout(() => {
target.apply(context, ...argumentsList);
}, delay);
runMap.set(context, timerId);
}
};
return new Proxy(fn, handler);
}
const createThrottle = function (fn, delay) {
let runMap = new Map();
const handler = {
apply: function (target, context, argumentsList) {
if (!runMap.has(context)) {
runMap.set(context, true);
setTimeout(() => {
runMap.delete(context);
}, delay)
target.apply(context, ...argumentsList);
} else {
console.log('runing, cancel this action!');
}
}
};
return new Proxy(fn, handler);
}
export {createDebounce, createThrottle};
<template>
<div>
<button @click="click">click</button>
<button @click="debounceClick">debounceClick</button>
<button @click="throttleClick">throttleClick</button>
after time: {{ time }}
</div>
</template>
<script>
import { createDebounce, createThrottle } from "fn";
export default {
data() {
return {
time: 0,
};
},
methods: {
click() {
let delay = Math.random() * 3000;
setTimeout(() => {
this.time = delay;
}, delay);
},
},
created() {
this.debounceClick = createDebounce(this.click, 300);
this.throttleClick = createThrottle(this.click, 1000);
},
};
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment