2021-06-26 01:35:40 +00:00
|
|
|
import type { Ref } from 'vue';
|
|
|
|
import { onMounted, ref } from 'vue';
|
2020-10-07 14:49:01 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Similar with `useLock`, but this hook will always execute last value.
|
|
|
|
* When set to `true`, it will keep `true` for a short time even if `false` is set.
|
|
|
|
*/
|
|
|
|
export default function useDelayReset(
|
|
|
|
timeout = 10,
|
|
|
|
): [Ref<Boolean>, (val: boolean, callback?: () => void) => void, () => void] {
|
|
|
|
const bool = ref(false);
|
|
|
|
let delay: number;
|
|
|
|
|
|
|
|
const cancelLatest = () => {
|
|
|
|
window.clearTimeout(delay);
|
|
|
|
};
|
|
|
|
|
2020-11-04 15:39:05 +00:00
|
|
|
onMounted(() => {
|
2020-10-07 14:49:01 +00:00
|
|
|
cancelLatest();
|
|
|
|
});
|
|
|
|
const delaySetBool = (value: boolean, callback: () => void) => {
|
|
|
|
cancelLatest();
|
|
|
|
delay = window.setTimeout(() => {
|
|
|
|
bool.value = value;
|
|
|
|
if (callback) {
|
|
|
|
callback();
|
|
|
|
}
|
|
|
|
}, timeout);
|
|
|
|
};
|
|
|
|
|
|
|
|
return [bool, delaySetBool, cancelLatest];
|
|
|
|
}
|