2023-07-27 07:31:52 +02:00
|
|
|
/*
|
2024-02-13 16:59:27 +01:00
|
|
|
* SPDX-FileCopyrightText: syuilo and misskey-project
|
2023-07-27 07:31:52 +02:00
|
|
|
* SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
*/
|
|
|
|
|
2024-01-20 13:23:33 +01:00
|
|
|
import { onActivated, onDeactivated, onMounted, onUnmounted } from 'vue';
|
2022-06-25 20:12:58 +02:00
|
|
|
|
|
|
|
export function useInterval(fn: () => void, interval: number, options: {
|
|
|
|
immediate: boolean;
|
|
|
|
afterMounted: boolean;
|
2023-01-04 19:28:25 +01:00
|
|
|
}): (() => void) | undefined {
|
2022-07-02 15:07:04 +02:00
|
|
|
if (Number.isNaN(interval)) return;
|
|
|
|
|
2022-06-25 20:12:58 +02:00
|
|
|
let intervalId: number | null = null;
|
|
|
|
|
|
|
|
if (options.afterMounted) {
|
|
|
|
onMounted(() => {
|
|
|
|
if (options.immediate) fn();
|
|
|
|
intervalId = window.setInterval(fn, interval);
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
if (options.immediate) fn();
|
|
|
|
intervalId = window.setInterval(fn, interval);
|
|
|
|
}
|
|
|
|
|
2023-01-04 19:28:25 +01:00
|
|
|
const clear = () => {
|
2022-06-25 20:12:58 +02:00
|
|
|
if (intervalId) window.clearInterval(intervalId);
|
2023-01-04 19:28:25 +01:00
|
|
|
intervalId = null;
|
|
|
|
};
|
|
|
|
|
2024-01-20 13:23:33 +01:00
|
|
|
onActivated(() => {
|
|
|
|
if (intervalId) return;
|
|
|
|
if (options.immediate) fn();
|
|
|
|
intervalId = window.setInterval(fn, interval);
|
|
|
|
});
|
|
|
|
|
|
|
|
onDeactivated(() => {
|
|
|
|
clear();
|
|
|
|
});
|
|
|
|
|
2023-01-04 19:28:25 +01:00
|
|
|
onUnmounted(() => {
|
|
|
|
clear();
|
2022-06-25 20:12:58 +02:00
|
|
|
});
|
2023-01-04 19:28:25 +01:00
|
|
|
|
|
|
|
return clear;
|
2022-06-25 20:12:58 +02:00
|
|
|
}
|