+ 4
Why the ball is automatically going upward when I click multiple times faster?
I have made a ball that should go downwards for the first click on the body. Then after the first click ,when it clicked on the body it should go upwards for 100ms and then again go downwards . But when I click multiple times faster, it's automatically going upward without going to downward after a certain time. Here is the code: https://code.sololearn.com/W9a13A14A21A Please help me to understand why it's happening and how to solve it. Thanks in advance.
7 RĂ©ponses
+ 1
When you do quick clicks , two intervals are set for move function without first one getting cleared .
Now when the time comes to clear the intervals , only first one is cleared instead you want it to clear both or otherwise second interval will keep working and pushing the object up .
Everytime we set an interval a different id is returned by it and then we use that id to clear the interval in future .
What you want to do is push all the interval ids into an array , after that get the specific id at a index in array and use clearInterval on it .
ââââââââââââââââââââ
Here is what i did .
var arr=[] ;// global object.
In body_modify(), in click event , in else clause :
j=setInterval(move,10);
arr.push(j);
In function move :
if(top==d-a){
clearInterval(arr.shift());
}
+ 2
Okay when I double click faster both functions will work, right? I mean body_modify[0].addEventListener() will work twice time.
So the array will store both ids and it will clear both the two ids that's why I don't have any problem while using an array.
In my code both use the same variables j so when two same functions occur at the same time one id is deleted that's why in my code it didn't work but storing it in the array doesn't overlap the values of it. So it deletes both ids.
@Abhay am I right?
+ 2
Thanks now it clears everything.
+ 1
Thanks @Abhay it works. I didn't know before that two same setInterval carries different ids.
I still have confusion. How does use array clears all the id.
+ 1
The future is now thanks to science[LESS ACTIVE]
Suppose there are two quick clicks then arr looks like this ,
arr=[id1, id2]
Now to clear those two intervals you need to get those ids .
arr.shift will remove the first element from the arr and return it , so we have id1 and we apply clearInterval to it .
arr now looks like, arr=[id2]
And so this goes on .
If you still don't understand something , feel free to ask.
+ 1
Yeah, I think I understand now. Thanks, I really appreciate your help.
+ 1
The future is now thanks to science[LESS ACTIVE] right .
Between one correction from my side .
When two or more intervals are set without others getting cleared then the clearInterval works on the last interval (which is obvious but i think i did a mistake by saying first one is cleared) instead of first interval .