Is it true that if possible I should never use setInterval & setTimeout?

后端 未结 3 2021
花落未央
花落未央 2021-02-09 10:54

I am learning to code in JavaScript. I am programming something with some timed mouse animation. I\'m just about to add some code which draws the mouse path.

It\'s going

3条回答
  •  庸人自扰
    2021-02-09 11:34

    I don't think using setInterval or setTimeout is bad practice. Using setTimeout is bad practice when you want to do something in future but you don't exactly know when you will be able to do that. For example this is bad practice:

    makeHeavyDomMovements();
    setTimeout(function () {
      //with 3000 timeout I'm sure any device has made my changes
      makeNextMove();
    }, 3000);
    

    the correct way was:

    makeHeavyDomMovements().
    then(function () {
       makeNextMove();
    });
    

    If you want to do something in future like respond to a user action 100ms later, it's best practice to use setTimeout or if you want to put something in browser queue, you should use setTimeout (or use a worker if needed).

    It's the same as setInterval, if you are using to do something that should be done every x milliseconds, well you are using it correctly and it's not bad practice, here is a bad usage of setInterval:

    var dbInterval = setInterval(function () {
      if (dbIsReady()) {
        clearInterval(dbInterval);
        fireReadyEvent();
      }
    }, 300);
    

    And here is a regular usage of setInterval:

    setInterval(function () {
      runSync();
    }, 600000);
    

    Bad practices and good practices are defied by the way you use your environment tools not those tools themselves.

提交回复
热议问题