2023-07-27 05:31:52 +00:00
|
|
|
/*
|
|
|
|
* SPDX-FileCopyrightText: syuilo and other misskey contributors
|
|
|
|
* SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
*/
|
|
|
|
|
2022-06-25 18:12:58 +00:00
|
|
|
import { onMounted, onUnmounted } from 'vue';
|
|
|
|
|
|
|
|
export function useInterval(fn: () => void, interval: number, options: {
|
|
|
|
immediate: boolean;
|
|
|
|
afterMounted: boolean;
|
2023-01-04 18:28:25 +00:00
|
|
|
}): (() => void) | undefined {
|
2022-07-02 13:07:04 +00:00
|
|
|
if (Number.isNaN(interval)) return;
|
|
|
|
|
2022-06-25 18:12:58 +00: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 18:28:25 +00:00
|
|
|
const clear = () => {
|
2022-06-25 18:12:58 +00:00
|
|
|
if (intervalId) window.clearInterval(intervalId);
|
2023-01-04 18:28:25 +00:00
|
|
|
intervalId = null;
|
|
|
|
};
|
|
|
|
|
|
|
|
onUnmounted(() => {
|
|
|
|
clear();
|
2022-06-25 18:12:58 +00:00
|
|
|
});
|
2023-01-04 18:28:25 +00:00
|
|
|
|
|
|
|
return clear;
|
2022-06-25 18:12:58 +00:00
|
|
|
}
|