Add Timeout / Sleep function inside javascript loop

耗尽温柔 提交于 2020-12-14 15:33:22

问题


I'm trying to add a sleep / delay function inside a js file, This one:

var webTest = function()
{

let regex = /^https?:\/\//;
let url = $('#list_urls').val().split('\n');
var xmlhttp = [], i;
var myObj2 = [], i;
 for(let i = 0; i < url.length; i++)
    {
    (function(i) {
    xmlhttp[i] = new XMLHttpRequest();
    url[i] = url[i].replace(regex, '');
    xmlhttp[i].open("GET", "https://website.com/API?key=<MY_API_KEY>&url="+url[i], false);
    xmlhttp[i].onreadystatechange = function() {
      if (xmlhttp[i].readyState === 4 && xmlhttp[i].status === 200) {
        myObj2 = JSON.parse(xmlhttp[i].responseText);
        document.getElementById("demo"+i).innerHTML = myObj2.results[1].categories;
      }
    };
xmlhttp[i].send();
})(i);
console.log(`The Server2: `+ myObj2);
 }
}

I want this script to pause for 10 second and then again do work and then again pause for 10 second and do like this untill text length is greater thatn i in loop! My code works if i run for single time but it doesn't works if i run in loop because the website has rate limit in the api so that's why i'm trying to add a sleep function.

So what i've tried is await sleep(); method and also tried setTimeout method but it's not working as expected in sort it doesn't works at all with my code!

await sleep(); just doesn't works at all and displays msg like Uncaught SyntaxError: await is only valid in async functions and async generators webTestfile.js:27


回答1:


You can make use of ES6's async/await-feature!

To use await, it needs to be in a function/expression body declared async.

Basically, this will make your function be asynchronous, and make it wait for a Promise to be fulfilled. We make that Promise be fulfilled after a set delay using setTimeout().
Note that "after a set delay" does not mean "exactly after", it basically means "as early as possible after".

By doing this, the asynchronous function waits for the promise to be fulfilled, freeing up the callstack in the meantime so that other code can be executed.

The order of execution of this example is (simplified) as follows:

  1. sleepingFunc() is placed on callstack
    • In iteration: await for Promise to be fulfilled, suspending this call 🡒 freeing up callstack
  2. Place new calls on callstack
  3. Eventually, Promise is fulfilled, ending await 🡒 place suspended call back on callstack
  4. Repeat until sleepingFunc() finished

As you can see in step 3, if other calls take up more time than the delay, the suspended call will have to wait that extra time longer.

function sleep(ms) {
  return new Promise(resolveFunc => setTimeout(resolveFunc, ms));
}

async function sleepingFunc() {
  for (let i = 0; i < 5; ++i) {
    console.log(i + " - from sleep");
    await sleep(1000);
  }
}

function synchronousFunc() {
  for (let i = 0; i < 5; ++i) {
    console.log(i + " - from sync");
  }
}

sleepingFunc();
synchronousFunc();



回答2:


This runs snippet runs one task every 1 second until the condition is satisfied, and then clears the timer.

const work = (i)=>{
 console.log('doing work here ', i);
}

let counter = 0
const timer = setInterval(()=>{
  if (timer && ++counter >= 10) {
   clearInterval(timer)
  }
  work(counter);
}, 1000)


来源:https://stackoverflow.com/questions/64995893/add-timeout-sleep-function-inside-javascript-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!