1

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

Vicky Malhotra
  • 340
  • 1
  • 4
  • 13
  • 2
    *I want this script to pause for 10 second and then again do work and then again pause for 10 second!* You cannot pause code. What you can do is run more code after a delay, but the currently running function on the call stack must complete before any new code can start. – Scott Marcus Nov 24 '20 at 22:40
  • Yeah i know that javascript doesn't have any sleep functionality but what can be done here to achieve at least 10-11second delay? tried setTimeout method but nothing worked :/ – Vicky Malhotra Nov 24 '20 at 22:43
  • This answer shows a [`sleep()`-alternative for JS in ES6](https://stackoverflow.com/a/39914235/13561410). – Oskar Grosser Nov 24 '20 at 22:45

2 Answers2

3

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();
Oskar Grosser
  • 2,804
  • 1
  • 7
  • 18
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)
Jkarttunen
  • 6,764
  • 4
  • 27
  • 29