Reputation: 1190
FYI: I know there are many "how can you call a method every X seconds using JavaScript" questions out there; this is slightly different so please don't mark as duplicate unless it truly is.
Problem: I have a method move
that takes in a direction parameter (i.e. r
,l
,u
,or d
). I want to call my move
method every X seconds with one parameter, but I want it to "cancel" the current move
interval that's running any other parameter. For example, if I'm running move('r')
every 1 second, and then I trigger the move('d')
event to run every 1 second, I want to cancel the move('r')
method.
Code:
$(document).keydown(function(event) {
if(event.which == RIGHT){
window.setInterval(function(){
//CANCEL OTHER CURRENT "MOVES" HERE
move('r');
}, 500);
} else if (event.which == LEFT) {
window.setInterval(function(){
//CANCEL OTHER CURRENT "MOVES" HERE
move('l');
}, 500);
} else if (event.which == UP){
window.setInterval(function(){
//CANCEL OTHER CURRENT "MOVES" HERE
move('u');
}, 500);
} else if (event.which == DOWN){
window.setInterval(function(){
//CANCEL OTHER CURRENT "MOVES" HERE
move('d');
}, 500);
}
});
Edit Thanks all for the awesome answers. A slight combination of a few answers below allowed me to finish up my project (well, almost) - http://jsfiddle.net/thomasmclaughlin/8c9ww/ - Thanks again!
Upvotes: 0
Views: 317
Reputation: 1098
Something like this would be better. Update variable simply, and pass it in the function.
$x = '';
$(document).keydown(function(event) {
if(event.which == RIGHT){
$x = 'r';
} else if (event.which == LEFT) {
$x = 'l';
} else if (event.which == UP){
$x = 'u';
} else if (event.which == DOWN){
$x = 'd';
}
});
window.setInterval(function(){
move($x);
}, 500);
Upvotes: 1
Reputation: 773
The way I'd personally go about it is completely different, but here goes a pseudocode/real code mixture:
var key = 0;
$(document).keydown(function(e) {
//check the event.which here, and set them to 1-4 depending on the event.which
});
$(document).keyup(function() {
key = 0;
});
$(document).ready(function() {
setInterval(move(key), 500);
});
Upvotes: 0
Reputation: 4669
Once consideration is to change your mathod of tracking the move. I suggest keeping your "move" in one small array, x and y. Set the current move by setting the x or why you wish to modify
'u' move=[-500,0]
'd' move=[500,0]
'l' move=[0,-500]
'd' move=[0,500]
Upvotes: 0
Reputation: 104775
Have a global timer variable setup for your interval
var myInterval = null;
Now have a method to set the interval, but first checking if one is in progress:
function startInterval(r, l, u, d) {
if (myInterval != null) clearInterval(myInterval)
myInterval = setInterval(function() {
move(r, l, u, d);
}, 500);
}
Now each time you call startInterval
, it will cancel the current interval if there is one and start a new one.
Upvotes: 4