English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I have a setInterval method inside a function that is activated on key down, and I want to clear the setInterval on key down. How do I do this????

2006-06-08 14:21:38 · 1 answers · asked by Anonymous in Computers & Internet Programming & Design

1 answers

Hmm. So a simulation would be "as soon as user presses key, block moves forward, user presses key again to stop block." ?
In that case, how about abusing javascript's loose casting:

var animId = null;

function moveBlock() {do stuff}

function startMotion() {
animId = setInterval("moveBlock()", 42);
}

function stopMotion() {
clearInterval(animId);
animId = null;
}

function switchMotion() {
if(animId)
stopMotion();
else
startMotion();
}

Then, attached to your body tag, you have the event onkeydown="switchMotion()". Be careful with what happens when a user holds a key down. The casted Boolean value of a variable is true if it is anything other than the empty string "", the number 0, undefined, null, NaN, or the Boolean value false. See http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Statements:if...else#Description .

2006-06-08 16:29:24 · answer #1 · answered by Ron 6 · 0 0

fedest.com, questions and answers