Execute the setInterval function without delay the first time

后端 未结 14 2153
故里飘歌
故里飘歌 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.

    0 讨论(0)
  • 2020-11-22 16:48

    You could wrap setInterval() in a function that provides that behavior:

    function instantGratification( fn, delay ) {
        fn();
        setInterval( fn, delay );
    }
    

    ...then use it like this:

    instantGratification( function() {
        console.log( 'invoked' );
    }, 3000);
    
    0 讨论(0)
提交回复
热议问题