Spaces:
Running
Running
File size: 1,257 Bytes
e6a9f90 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | import { useState, useEffect, useRef } from 'react';
import { Section } from '../types/Conversation';
export const useScrollTimer = (sections: Section[]) => {
const [activeIndex, setActiveIndex] = useState(0);
const timerRef = useRef<number | null>(null);
const startTimer = () => {
if (sections.length <= 1) return;
const nextSection = () => {
setActiveIndex((prevIndex) => (prevIndex + 1) % sections.length);
};
// Clear any existing timer
if (timerRef.current !== null) {
window.clearTimeout(timerRef.current);
}
// Set new timer based on current section's duration
const currentDuration = sections[activeIndex]?.duration || 10;
timerRef.current = window.setTimeout(nextSection, currentDuration * 1000);
};
// Start/restart timer when activeIndex changes or component mounts
useEffect(() => {
startTimer();
// Cleanup timer on unmount
return () => {
if (timerRef.current !== null) {
window.clearTimeout(timerRef.current);
}
};
}, [activeIndex, sections]);
const goToSection = (index: number) => {
if (index >= 0 && index < sections.length) {
setActiveIndex(index);
}
};
return {
activeIndex,
goToSection
};
}; |