How to use setInterval and clearInterval?

前端 未结 5 927
盖世英雄少女心
盖世英雄少女心 2020-11-22 03:58
function doKeyDown(event) {
    switch (event.keyCode) {
    case 32:
        /* Space bar was pressed */
        if (x == 4) {
            setInterval(drawAll, 20);         


        
5条回答
  •  悲&欢浪女
    2020-11-22 04:25

    setInterval sets up a recurring timer. It returns a handle that you can pass into clearInterval to stop it from firing:

    var handle = setInterval(drawAll, 20);
    
    // When you want to cancel it:
    clearInterval(handle);
    handle = 0; // I just do this so I know I've cleared the interval
    

    On browsers, the handle is guaranteed to be a number that isn't equal to 0; therefore, 0 makes a handy flag value for "no timer set". (Other platforms may return other values; NodeJS's timer functions return an object, for instance.)

    To schedule a function to only fire once, use setTimeout instead. It won't keep firing. (It also returns a handle you can use to cancel it via clearTimeout before it fires that one time if appropriate.)

    setTimeout(drawAll, 20);
    

提交回复
热议问题