javascript Call function 10 times with 1 second between

前端 未结 8 1721
花落未央
花落未央 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-24 18:11

    function callNTimes(func, num, delay) {
        if (!num) return;
        func();
        setTimeout(function() { callNTimes(func, num - 1, delay); }, delay);
    }
    callNTimes(callfunction, 10, 1000);
    

    EDIT: The function basically says: make a call of the passed function, then after a bit, do it again 9 more times.

提交回复
热议问题