File size: 1,330 Bytes
1e8f4c6 |
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 48 49 50 51 52 53 54 55 56 57 58 59 |
import { useState, useEffect, useCallback } from "react";
export const useSlotMachine = ({
items = [],
duration = 2000,
interval = 50,
}) => {
const [currentIndex, setCurrentIndex] = useState(0);
const [isSpinning, setIsSpinning] = useState(false);
const [isStopped, setIsStopped] = useState(false);
const spin = useCallback(() => {
if (!items.length) return;
setIsSpinning(true);
setIsStopped(false);
let startTime = Date.now();
let currentTimer;
const updateSlot = () => {
const now = Date.now();
const elapsed = now - startTime;
if (elapsed >= duration) {
setIsSpinning(false);
setIsStopped(true);
return;
}
// Calculer la vitesse de rotation en fonction du temps écoulé
const speed = Math.max(1, Math.floor((duration - elapsed) / 200));
setCurrentIndex((prev) => (prev + speed) % items.length);
currentTimer = setTimeout(updateSlot, interval);
};
updateSlot();
return () => {
if (currentTimer) {
clearTimeout(currentTimer);
}
};
}, [items, duration, interval]);
const getCurrentItem = useCallback(() => {
return items[currentIndex];
}, [items, currentIndex]);
return {
currentItem: getCurrentItem(),
isSpinning,
isStopped,
spin,
};
};
|