Created
January 24, 2022 05:11
-
-
Save muedsa/217bb8f0bf556e00a67952c69eda00dc to your computer and use it in GitHub Desktop.
debounc throttle by Proxy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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