JavaScript setInterval immediately run

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

提交回复
热议问题