I have a JS sprite animation that I use with an interval, since transform and transitions are not available. Whenever the backgroundPosition
goes back to the start, there is a brief delay where the image disappears. I put the code in a codesandbox to make sure it works as expected, and I’m not seeing that behavior there: pedantic-ramanujan-ujn1e - CodeSandbox
import test2 from "./test2.png";
export default function App() {
const inputEl = useRef(null);
const posRef = useRef(25);
useInterval(() => {
inputEl.current.style.backgroundPosition = `-${posRef.current}px 0px`;
if (posRef.current < 200) {
posRef.current = posRef.current + 25;
}
//we increment the position by 25 each time
else {
posRef.current = 25;
}
//reset the position to 25px, once position exceeds 200px
}, 220);
return (
<div className="App">
<p
id="image"
ref={inputEl}
style={{
background: `url(${test2}) 0px 0px`,
width: "25px",
height: "25px"
}}
></p>
</div>
);
}
function useInterval(callback, delay) {
const savedCallback = useRef();
useEffect(() => {
savedCallback.current = callback;
});
useEffect(() => {
function tick() {
savedCallback.current();
}
let id = setInterval(tick, delay);
return () => clearInterval(id);
}, [delay]);
}