Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
126
rated 0 times [  128] [ 2]  / answers: 1 / hits: 5718  / 4 Years ago, tue, november 24, 2020, 12:00:00

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


More From » arrays

 Answers
6

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();




[#2235] Friday, November 20, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ibrahimgilbertoz

Total Points: 420
Total Questions: 112
Total Answers: 92

Location: Bonaire
Member since Sat, May 1, 2021
3 Years ago
;