Home >Web Front-end >JS Tutorial >How Can I Use `clearInterval` to Prevent `setInterval` from Creating an Unwanted Loop in My `doKeyDown` Function?
Utilizing the setInterval and clearInterval functions
When considering the following block of code:
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; } }
The goal is to solve the problem in the code It is hoped that the drawAll() function will only be called once, rather than creating a loop that continuously calls the function.
How to use clearInterval
In order to solve this problem, you can use the clearInterval function. The setInterval function sets a repeating timer and returns a handle that can be passed to clearInterval to stop the timer:
var handle = setInterval(drawAll, 20); // 当需要取消计时器时: clearInterval(handle); handle = 0; // 这样可以得知已经清除了计时器
In browsers, the handle is guaranteed to be a number not equal to 0; therefore, 0 is a convenience flag value that means "timer is not set". (Other platforms may return other values; for example, Node.js's timer function returns an object.)
Use setTimeout
To schedule a timer that will only fire once function, you can use the setTimeout function. It doesn't trigger continuously. (It also returns a handle, where appropriate, you can use clearTimeout if you need to cancel the function before it fires once).
setTimeout(drawAll, 20);
The above is the detailed content of How Can I Use `clearInterval` to Prevent `setInterval` from Creating an Unwanted Loop in My `doKeyDown` Function?. For more information, please follow other related articles on the PHP Chinese website!