[removed] Is it ok to call cleartimeout before settimeout?

前端 未结 5 1470
滥情空心
滥情空心 2021-02-18 19:05

I have a function that sets a timer, and calls itself back upon expiration of the timer.

What I\'d like to know is if it is bad practice to clear the timer at the top o

相关标签:
5条回答
  • 2021-02-18 19:46

    Yes, that's fine. Also, you should call "setTimeout()" like this:

      timer = setTimeout(onAir, 60000);
    
    0 讨论(0)
  • 2021-02-18 19:46

    Yes you can call clearTimeout on a nullvariable.

    Also i would suggest you change your setTimeout so it won't use eval:

    timer = setTimeout(onAir,60000);
    
    0 讨论(0)
  • 2021-02-18 19:47

    Yes, you can call a clearTimeout on a null variable and the world won't implode.

    0 讨论(0)
  • 2021-02-18 19:52

    Yes you can call clearTimeout(timer), but there are some edge cases where it may cause issues.

    If timer had been previously set with some other integer value, you might be killing off a completely unrelated timer.

    setTimeout just returns an integer index for the timer. If you're not sure if a timer has been previously set, you could add a check before calling clearTimeout:

    if (window.timer)
    {
      clearTimeout(timer);
    }
    ...
    timer = setTimeout(onAir, duration);
    

    A solution to the possible pollution of the timer variable is to use a closure:

    (function(){
      var timer,
        duration;
      duration = 60000;
      window.onAir = function onAir(){
        ...code...
        if (timer){
          clearTimeout(timer);
        }
        timer = setTimeout(onAir,duration);
      };
    });
    
    0 讨论(0)
  • 2021-02-18 20:13

    Clearing a Timeout raises not problem to me (but i am not a javascript guru).

    Btw, you can find intersting things (checking an existing Timeout) on this thread: Check if a timeout has been cleared?

    0 讨论(0)
提交回复
热议问题