setInterval - How to fire only once?

后端 未结 2 605
感动是毒
感动是毒 2021-01-18 06:59

Hello I have this snippet of code that will fire some even after time that I choose.

The problem is that if, for example I put 3 seconds it will fire every 3 seconds

相关标签:
2条回答
  • 2021-01-18 07:13

    You don't need setInterval, you need setTimeout.

    As the name says, setInterval fires regularly, while setTimeout fires only once. The usage is the same though.

    0 讨论(0)
  • 2021-01-18 07:29

    Use setTimeout instead, it works almost the same but will only fire once. You have clearTimeout and setTimeout so its very similar to setInterval

    function playSound(timeLeft){
       var sendDataTimeout = function(){
          alert('OK');
       }
       setTimeout(sendDataTimeout, timeLeft);
    }
    

    You don't have to use clearTimeout anymore. But FYI it exist and works the same as clearInterval.

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