I want to increase my variable to 100 & then decrease to 0 automatically after each scrolling event. but I do not want this processing to be in a moment, but to happen smoothly .
I tried a little but I did not succeed I want something like the following code:
useEffect(() =>
{
window.addEventListener('scroll', function()
{
// setStartRotate(true)
for (let i = 0; i < 100; i ) {
setValue(pre=>pre 1)
}
for (let i = value; i < 0; i--) {
setValue(pre=>pre-1)
}
}, true)
})
CodePudding user response:
As you are working in React, have you tried using a component with a onScroll={yourFunction}
?
This should work better than an addEventListener.
Then:
const yourFunction = () => {
//Increase and decrease variables here
}.
CodePudding user response:
To make this you should use timeout (MDN post). Also loops are synchronous, so you cannot stop it for several seconds. For this reason, write your own asyncLoop
:
const asyncLoop = (start, end, eventFunc, eventSuccess, callback, endFunc) => {
let s = start;
let e = end;
let done = false;
let aLoop = {
next: () => {
if (done) {
return;
}
if (eventFunc(s, e)) {
s = eventSuccess(s);
callback(aLoop, s);
} else {
done = true;
endFunc && endFunc();
}
}
};
aLoop.next();
return aLoop;
};
After that you can easily call setValue
function to increase or decrease your number. All code here (Sorry, I use click event for the tests)