Consider:
function doKeyDown(event) {
switch (event.keyCode) {
case 32:
/* Space bar was pressed */
if (x == 4) {
setInterval(drawAll, 20);
}
else {
setInterval(drawAll, 20);
x += dx;
}
break;
}
}
I want to call drawAll() once, not creating a loop that call drawAll again and again. Should I use a recursive method for that or should I use clearInterval?
How can I use clearInterval?
setIntervalsets up a recurring timer. It returns a handle that you can pass intoclearIntervalto stop it from firing:On browsers, the handle is guaranteed to be a number that isn’t equal to
0; therefore,0makes a handy flag value for "no timer set". (Other platforms may return other values; Node.js’s timer functions return an object, for instance.)To schedule a function to only fire once, use
setTimeoutinstead. It won’t keep firing. (It also returns a handle you can use to cancel it viaclearTimeoutbefore it fires that one time if appropriate.)