Simple script
I have a list, I implemented a scan using the arrow keys (up, down) and every time I change the current list item, the database object is loaded via AJAX.
Sweet.
Problem
When the user browses the list very quickly, I do not want every request to leave. But the original request should go away instantly, of course.
My idea was to set a timeout using the variable as a delay, and after the initial loading of the element, increase this variable.
This works, but when the user stops browsing for a short time, but then continues, I still donβt want every request to leave.
So, I realized that the delay variable should be reasonably increased with each event view until the threshold is reached.
This organic approach will minimize the amount of unnecessary loading of items.
My decision
I have gone far. This piece of code (explanation below) will do the job with one main culprit :
After the first viewing and stopping session, the delay will automatically remain at the minimum value (2nd step) of 150 ms.
Of course, I tried to fix it, but, as you will see, this is an interesting, but probably quite general logical problem - and I think my general approach is wrong.
But I do not understand how to do this. The brain is not calculated. The computer says no.
the code
You can sift through my above example or go here for a fully functional simulator in jsFiddle .
If you select jsFiddle:
Click the button, the item will immediately load. Now wait a bit, press the button again, the initial load will be delayed. If you constantly press the button quickly, the load of the item will be displayed only when you finish your click.
Code example
We are inside an object literal just to let you know.
_clickTimer: false,
Explanation
On the first call: _clickTimer
is false
, _timerInc
is 0
, so the first call will delay 0
for setTimeout()
and _clickTimer
. The item will be downloaded instantly.
The second call is provided that our timeout is still waiting for it to _clickTimer
, _clickTimer
will be cleared, the delay is set to 150
if 0
or increased by 15
if below 350
(threshold).
This works great if you keep browsing. The timer increases, the load starts only after stopping viewing for a good moment.
But after you stop, the next time you continue, _clickTimer
will not be false (because setTimeout()
assigns a counter to it), therefore, in turn, _timerInc
will be immediately set to 150
. Thus, the first scan will result in a delay of 150 ms before anything loads.
Call me crazy or finicky, but the goal is not to delay this delay.
Of course you say: simple, set _clickTimer
to false at the end of the setTimeout()
close, so it gets reset after viewing and loading the element. Great, but this leads to a delay never exceeding 0 ms. Think about it, you will see.
I hope that this has been explained correctly and that someone's brain is more capable of finding a solution to this than mine.