JavaScript setInterval immediately run

前端 未结 5 1845
梦如初夏
梦如初夏 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:13

    If you add the parenthesis to the below code part it does

        doMagic: function () {
            setInterval(function magic() {
                console.log('magic');
                return magic;
            }(), 2500);                   // added them here
        }
    
    0 讨论(0)
  • 2021-01-22 10:14

    Try this example

    var hello = function() {
      document.write('hello... ');
    };
    setInterval(hello, 1000);
    hello();

    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
  • 2021-01-22 10:27

    In your code there is no way to perform the required task, instead follow the below approach:

    // Use function to perform the task.
    function doTask () {
    	console.log("...");
    }
    // Perform task for the first time.
    doTask();
    // On interval do task.
    setInterval(doTask, 2500);

    0 讨论(0)
  • 2021-01-22 10:34

    Perhaps the most proper way to do it would be to take the whole callback outside of the setInterval call and put it in a separate variable:

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

    The effect is the same as your first code, but this way your code is a little cleaner.

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