javascript Call function 10 times with 1 second between

前端 未结 8 1715
花落未央
花落未央 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:05
    setInterval(function(){},1000);
    

    Calls the function for every second...

    You can also use setTimeout for your thing to work.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-24 18:15

    Another solution

    for(var x=0; x<10; x++) window.setTimeout(callfunction, 1000 * x);
    
    0 讨论(0)
  • 2021-01-24 18:16

    You can try to use setInterval and use a variable to count up to 10. Try this:

    var number = 1;
    function oneSecond () {
      if(number <= 10) {
        // execute code here..
        number++;
      }
    };
    

    Now use the setInterval:

    setInterval(oneSecond, 1000);
    
    0 讨论(0)
提交回复
热议问题