JavaScript setInterval immediately run

前端 未结 5 1851
梦如初夏
梦如初夏 2021-01-22 09:28

I found a solution to run interval in javascript immidiately, not waiting for a first \"timeout\"

setInterval(function hello() {
  console.log(\'world\');
  retu         


        
5条回答
  •  广开言路
    2021-01-22 10:19

    Your no longer self-executing the function in your 2nd code snippet. You need to change this to the following:

    doMagic: function () {
       setInterval(function magic() {
          console.log('magic');
          return magic;
       }(), 2500);
    }
    

    I agree with others though, this isn't the cleanest way to do this and isn't very obvious to the next developer who comes along. I recommend storing the function in a variable, executing it immediately and then running it in the setInterval also:

    doMagic: function () {
       var magic = function magic() {
          console.log('magic');
          return magic;
       }
       magic();
       setInterval(magic, 2500);
    }
    

提交回复
热议问题