How do you deal with subsequent events in JavaScript when the previous one has not yet finished processing?
How do you deal with subsequent events in JavaScript when the previous one has not yet finished processing?
I h开发者_运维技巧ave a textbox with the onkeyup
event defined. When the event occurs it invokes a function that can take longer to process than it can for the next onkeyup
event to fire in most situations.
Is there a solid way of interrupting/abandoning the previous onkeyup
event and just start on the next one?
Javascript works like a GUI so no two events are processed at the same time.
The best solution if your processing is too heavy in my opinion would be changing your it so that it can be performed in small steps. Then when you get a keyup event you just do the first step and each step does a setTimeout
call with a zero delay to trigger next step
This way restarting your computation is trivial.
It works because timeouts always are the lowest priorities (i.e. if there will be another keyup this will be processed immediately and you will restart the computation instead of continuing the previous one).
You could do something along this line:
var isRunning = false;
var i = 0;
function runFunc() {
i++;
if (isRunning == false) {
isRunning = true;
keepRunning();
}
}
function keepRunning() {
while (i > 0) {
realProcessing();
i--;
}
isRunning = false;
}
var el = document.getElementById('field');
el.onkeyup = runFunc;
keepRunning() will keep executing the real processing function as many times as the keyup event was fired
I wrote this off my mind and didn't test it (shame on me), but this way you can probably achieve your results (or with something similar).
ps: I still think that you can have concurrency issues with the code above, and I'd be very interested in finding solutions to those (or someone proving me that there are no concurrency issues).
精彩评论