Execute the setInterval function without delay the first time

后端 未结 14 2351
故里飘歌
故里飘歌 2020-11-22 16:17

It\'s there a way to configure the setInterval method of javascript to execute the method immediately and then executes with the timer

14条回答
  •  猫巷女王i
    2020-11-22 16:45

    // YCombinator
    function anonymous(fnc) {
      return function() {
        fnc.apply(fnc, arguments);
        return fnc;
      }
    }
    
    // Invoking the first time:
    setInterval(anonymous(function() {
      console.log("bar");
    })(), 4000);
    
    // Not invoking the first time:
    setInterval(anonymous(function() {
      console.log("foo");
    }), 4000);
    // Or simple:
    setInterval(function() {
      console.log("baz");
    }, 4000);

    Ok this is so complex, so, let me put it more simple:

    function hello(status ) {    
      console.log('world', ++status.count);
      
      return status;
    }
    
    setInterval(hello, 5 * 1000, hello({ count: 0 }));

提交回复
热议问题