Execute the setInterval function without delay the first time

后端 未结 14 2167
故里飘歌
故里飘歌 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条回答
  •  死守一世寂寞
    2020-11-22 16:32

    For someone needs to bring the outer this inside as if it's an arrow function.

    (function f() {
        this.emit("...");
        setTimeout(f.bind(this), 1000);
    }).bind(this)();
    

    If the above producing garbage bothers you, you can make a closure instead.

    (that => {
        (function f() {
            that.emit("...");
            setTimeout(f, 1000);
        })();
    })(this);
    

    Or maybe consider using the @autobind decorator depending on your code.

提交回复
热议问题