javascript Call function 10 times with 1 second between

前端 未结 8 1824
花落未央
花落未央 2021-01-24 17:40

How to call a function 10 times like

for(x=0; x<10; x++) callfunction();

but with 1 sec between each call?

8条回答
  •  庸人自扰
    2021-01-24 18:06

    Similar to Amadan's answer but with a different style of closure which means you re-use instead of creating new functions

    function call(fn, /* ms */ every, /* int */ times) {
        var repeater = function () {
            fn();
            if (--times) window.setTimeout(repeater, every);
        };
        repeater(); // start loop
    }
    // use it
    var i = 0;
    call(function () {console.log(++i);}, 1e3, 10); // 1e3 is 1 second
    // 1 to 10 gets logged over 10 seconds
    

    In this example, if you were to set times to either 0 or Infinity, it would run forever.

提交回复
热议问题