javascript Call function 10 times with 1 second between

前端 未结 8 1717
花落未央
花落未央 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

    You can use setInterval for repeated execution with intervals and then clearInterval after 10 invocations:

    callfunction();
    var callCount = 1;
    var repeater = setInterval(function () {
      if (callCount < 10) {
        callfunction();
        callCount += 1;
      } else {
        clearInterval(repeater);
      }
    }, 1000);
    

    Added: But if you don't know how long it takes your callfunction to execute and the accurate timings between invocation starting points are not important it seems it's better to use setTimeout for reasons mentioned by Paul S and those described in this article.

提交回复
热议问题