I''m getting input as a stream of x/y coords, and I'd like to trigger an event if those coords fall within a specified range for a given period of time (say 2 seconds). Could someon开发者_如何学Goe suggest a way to do this?
Algorithmically, when you first detect that it's in the range, you do a setTimeout()
for 2 seconds. From then on, if the coords stay in the bounds and the timer is already set, you do nothing. If the coords fall outside the bounds, you stop the timer with clearTimeout()
. If the timer fires before you've cleared it, then the coords have stayed in the bounds for the desired time.
Here's a code example:
var myTimer = null;
function processCoordinatePair(x,y) {
if (inBounds(x,y)) {
if (!myTimer) {
setTimeout(function() {
// we stayed in bounds for 2 seconds, do whatever needs doing
myTimer = null; // clear timer for future use
}, 2000);
}
} else { // not in bounds any more
if (myTimer) {
clearTimeout(mytimer); // if timer was running, stop it
myTimer = null;
}
}
}
The implementation of the inBounds()
function is obviously up to you since you haven't described that part of the problem.
精彩评论