不可阻挡的循环

时间:2019-02-08 23:49:27

标签: javascript php

我通过添加代码改进了这个问题。

我坚持不停地循环,请帮助我。

我正在呼叫5个api网址:

每个网址都应使用特定的号码进行调用:

URL1 should be called 4 times
URL2 should be called 10 times
URL3 should be called 8 times
URL4 should be called 9 times
URL5 should be called 6 times

请在下面查看我的代码: https://www.codepile.net/pile/7Plo91MN

该循环应从URL1开始,当到达URL5时,则应再次从URL1开始,这是不可阻挡的。

2 个答案:

答案 0 :(得分:0)

在这里,您将需要添加URL调用代码。

let arrUrls = [
  ["URL1", 4],
  ["URL2", 10],
  ["URL3", 8],
  ["URL4", 9],
  ["URL5", 6]
];

let sendNum = 0;

function callUrl(url, rpt){
  for (let i = 0; i < rpt; i++) {
    // calling code
    console.log(`called ${url} - ${i}/${sendNum}`);
  }
};

let x = 0;
while(x<4) // Change this to while(true) for infinite loop
{
  sendNum = 0;
  arrUrls.forEach(u => {
    sendNum++;
    callUrl(u[0], u[1]);
  });
  x++;
}

根据客人的评论。这是更友好的UI版本。另外,为了方便起见,我还添加了3秒睡​​眠和一个停止按钮。

document.querySelector('button').addEventListener('click', (e) => {
  if(interval !== undefined) {
    clearInterval(interval);
    console.log('Stopped !!');
  }
});

let arrUrls = [
  ["URL1", 4],
  ["URL2", 10],
  ["URL3", 8],
  ["URL4", 9],
  ["URL5", 6]
];

let sendNum = 0;
let interval = undefined;

function callUrl(url, rpt) {
  let count = 0;
  for (let i = 0; i < rpt; i++) {
    // calling code
    count++;
  }    
  console.log(`called ${url} - ${count} times - on loop: ${sendNum}`);
};


interval = setInterval(() => // Change this to while(true) for infinite loop
{
  console.clear();
  sendNum++;
  arrUrls.forEach(u => {
    callUrl(u[0], u[1]);
  });
}, 3000);
<button>Stop Me</button>

答案 1 :(得分:0)

在PHP中,您可以使用InfiniteIterator。令人惊讶的是,它可以无限迭代。

$urls = ['url1' => 4, 'url2' => 10, 'url3' => 8, 'url4'=> 9, 'url5' => 6];

$unstoppable = new InfiniteIterator(new ArrayIterator($urls));

foreach ($unstoppable as $url => $times) {
    for ($i = 0; $i < $times; $i++) {
        // call $url
    }
}

您将被禁止访问其中的每个URL!