Execute the setInterval function without delay the first time

后端 未结 14 2366
故里飘歌
故里飘歌 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:47

    There's a problem with immediate asynchronous call of your function, because standard setTimeout/setInterval has a minimal timeout about several milliseconds even if you directly set it to 0. It caused by a browser specific work.

    An example of code with a REAL zero delay wich works in Chrome, Safari, Opera

    function setZeroTimeout(callback) {
    var channel = new MessageChannel();
    channel.port1.onmessage = callback;
    channel.port2.postMessage('');
    }
    

    You can find more information here

    And after the first manual call you can create an interval with your function.

提交回复
热议问题