代码之家  ›  专栏  ›  技术社区  ›  Hernan Humaña

如何在javascript数组中每5分钟调用一个函数

  •  1
  • Hernan Humaña  · 技术社区  · 6 年前

    我有一个包含任何参数的数组,例如: let EveryTen = ['a,'b','c']

      EveryTen.forEach(element => {
        setDelay(element)
      });
    
    
    const setDelay = (element) => {
       setTimeout(function(){
         UpdateDataPost(element); //Function A
         UpdateDataBasic(element); //Function B
       }, 60 * 5 * 1000);
    }
    

    6 回复  |  直到 6 年前
        1
  •  1
  •   kyle    6 年前

    这是一个很好的用例 setInterval ,我们只定义它运行的时间间隔(5分钟),并将其添加到事件循环中。知道了这一点,我们可以采取一点不同的方法,使用计数器来跟踪传递的间隔数,这允许我们处理每个bucket。

    const everyTen = ['a', 'b', 'c'];
    
    const updateDataPost = (data) => {
      console.log(`updateDataPost ${data}`);
    };
    
    const updateDataBasic = (data) => {
      console.log(`updateDataBasic ${data}`);
    };
    
    let intervalsPassed = 0;
    
    const interval = setInterval(() => {
      const currentBucket = everyTen[intervalsPassed++];
      updateDataPost(currentBucket);
      updateDataBasic(currentBucket);
      if (intervalsPassed >= everyTen.length) {
        console.log('no more buckets, stopping interval')
        clearInterval(interval);
      }
    }, 1000 * 60 * 5);
    

    输出:

    "updateDataPost a"
    "updateDataBasic a"
    
    "updateDataPost b"
    "updateDataBasic b"
    
    "updateDataPost c"
    "updateDataBasic c"
    

    这是一个JS bin,我设置为5秒,使它更快地测试 https://jsbin.com/fafewelufi/edit?js,console

        2
  •  1
  •   Kevin Lewis    6 年前

    setInterval(function(){
         UpdateDataPost(element); //Function A
         UpdateDataBasic(element); //Function B
       }, 1000*60*5);
    

    如果每次都要更新不同的元素,我会在函数中包含某种计数器。举个例子:

    var i = 0;
    setInterval(function(){
         UpdateDataPost(EveryTen[i]); //Function A
         UpdateDataBasic(EveryTen[i]); //Function B
         i++;
       }, 1000*60*5);
    

    如果您想在每个项目使用后停止,那么这可能是最好的方法:

    var i = 0;
    
    var interval = setInterval(function(){
         if(i <EveryTen.length) {
           UpdateDataPost(EveryTen[i]); //Function A
           UpdateDataBasic(EveryTen[i]); //Function B
           i++;
         } else {
            clearInterval(interval);
         }
       }, 1000*60*5);
    
        3
  •  1
  •   taylorcressy    6 年前

    我觉得这是一个递归的问题:)

    你为什么不打电话 setDelay 在内部 setInterval ? 以您的例子:

     EveryTen.forEach(element => {
       setDelay(element)
     });
    
    
     const setDelay = (element) => {
        setTimeout(function(){
           UpdateDataPost(element); //Function A
           UpdateDataBasic(element); //Function B
           setDelay(element);   // Added this.
        }, 60 * 5 * 1000);
     }
    

    设置间隔 :

    const startInterval = (element) => {
       setInterval(function(){ 
           // Do something
       }, 60 * 5 * 1000);
    }
    
        4
  •  1
  •   user3589620 user3589620    6 年前

    所有值的函数

    var arr = ["a", "b", "c"];
    
    function output(val) {
      console.log(val);
    }
    
    function setTimeouts(arr, ms, f) {
      arr.forEach(function(val, i) {
        setTimeout(function() {
          f(val);
        }, ms * (i + 1));
      });
    }
    
    // Change 3000 -> 1000 * 60 * 5
    setTimeouts(arr, 3000, output);

    用一个 习俗 每个值的函数

    var arr = ["a", "b", "c"];
    
    function f1(val) {
      console.log("This is f1 with val: " + val);
    }
    
    function f2(val) {
      console.log("This is f2 with val: " + val);
    }
    
    function f3(val) {
      console.log("This is f3 with val: " + val);
    }
    
    function setTimeouts(arr, ms, fns) {
      arr.forEach(function(val, i) {
        setTimeout(function() {
          fns[i](val);
        }, ms * (i + 1));
      });
    }
    
    // Change 3000 -> 1000 * 60 * 5
    setTimeouts(arr, 3000, [f1, f2, f3]);
        5
  •  1
  •   Janil    6 年前

    从我收集的信息来看,您只希望每5分钟处理一个元素,直到最后一个元素被完全处理。我的建议是:

    const ProcessListInInterval = (interval, list, callback) => {
      // Sets a delay for the element at the `index` position
      const setDelay = (index) => {
        // Only sets the delay if index < 0
        if (index < list.length) {
          setTimeout(() => {
            const element = list[index];
            // Process element
            callback(element);
    
            // Sets delay for the next index, you could potentially add code
            // to reset the index here, if you don't want this to ever stop
            setDelay(time, index + 1);
          }, interval);
        }
      };
    
      // Start from index 0
      setDelay(0);
    };
    
    ProcessListInInterval(300000 /* 5 * 60 * 1000 */, EveryTen, (element) => {
      // Do processing here
    });
    

    这可能和 setInterval 我也是,但我喜欢这样是因为三个原因:

    1. ProcessListInInterval
    2. 它是通用的和可重用的

    我也是一个 functional programming 所以我更喜欢这种不变性+递归的风格。

        6
  •  1
  •   marzelin    6 年前

    function wait(ms) {
      return new Promise((res) => setTimeout(res, ms));
    }
    
    async function main() {
      for (const element of EveryTen) {
        update(element);
        await wait(5 * 1000); // wait 5 seconds for example purposes
      }
    }
    
    
    // below not relevant specific implementation details
    
    
    function update(element) {
      UpdateDataPost(element); //Function A
      UpdateDataBasic(element); //Function B
    }
    
    function UpdateDataPost(element) {
      element.textContent = `updated at ${new Date()}`
    }
    
    function UpdateDataBasic(element) {
      document.querySelector(".basic").textContent = `updated at ${new Date()}`
    }
    
    const EveryTen = Array.from(document.querySelectorAll(".post"));
    
    main();
    <h2>post 1</h2>
    <p class="post">post not updated</p>
    <h2>post 2</h2>
    <p class="post">post not updated</p>
    <h2>post 3</h2>
    <p class="post">post not updated</p>
    <h2>post 4</h2>
    <p class="post">post not updated</p>
    <h2>post 5</h2>
    <p class="post">post not updated</p>
    <h2>Basic</h2>
      <p class="basic">basic not updated</p>