I'm detecting a scroll end with clearTimeout.
const Component= ({container}) => {
const timeoutRef = useRef<number>(0)
const handleScroll = {
clearTimeout(timeoutRef.current)
timeoutRef.current = setTimeout(function () {
if(!timeoutRef.current){ // 'no scroll in progress, do something' }
}, 100)
}
useEffect(() => {
container.addEventListener('scroll', handleScroll, true)
}, [])
}
But the timeoutRef is not reset when scrolling again, instead, its value only increases. How to fix that?
That is how setTimeout works. Every time you generate a timeout it generates a new identifier. You use that identifier to cancel the timeout. The timeout does not clear the variable.
If the setTimeout fires, that means it was not cancelled. In your case that means the user did stop scrolling.
timeoutRef.current = setTimeout(function () {
console.log('User is done scrolling');
}, 100)