0

I need it to pause for 3 seconds at the end of every loop, but it's not pausing. How do I fix this? Example codes would be appreciated.

function file_get_contents(url, callback) {
  fetch(url).then(res => res.text()).then(text => callback(text));
}

function theCallBack(text) {
  text = text.replace(/google/g, "")
  let matches = text.match(/www.[a-z\-]+?.com/g);
  console.log(matches[0]);
};

var theArray = ["https://www.google.com/search?q=one", "https://www.google.com/search?q=two", "https://www.google.com/search?q=three"];
var count = theArray.length;

while (count > 0) {
  console.log(count);
  count--;
  file_get_contents(theArray[count], theCallBack);
  setTimeout(function() {}, 3000);
}

3
  • What do you need to pause? Commented Oct 30, 2021 at 7:21
  • 1
    while loops do not wait for setTimeouts Commented Oct 30, 2021 at 7:22
  • 3 seconds at the end of every loop, Do you mean 3 seconds at the end of every successful fetch() ? Commented Oct 30, 2021 at 7:25

2 Answers 2

1

You can use a Promise to pause the program and await it.

const wait = (ms) => new Promise(resolve => setTimeout(resolve, ms));


function file_get_contents(url, callback) {
  fetch(url).then(res => res.text()).then(text => callback(text));
}

function theCallBack(text) {
  text = text.replace(/google/g, "")
  let matches = text.match(/www.[a-z\-]+?.com/g);
  console.log(matches[0]);
};

var theArray = ["https://www.google.com/search?q=one", "https://www.google.com/search?q=two", "https://www.google.com/search?q=three"];
var count = theArray.length;



(async() => {
  for (let i = 0; i < count; i++) {
    console.log(i + 1);
    file_get_contents(theArray[i], theCallBack);
    await wait(3000);
  }
})();

Sign up to request clarification or add additional context in comments.

3 Comments

There's a fail to load resource error. If you run code snippet it will also only show 1, 2, 3.
I found the error, need to replace theArray[count] with theArray[i]
lol thx for pointing out. Fixed now!
0

I think problem is setTineout() async function, so you need make it sync, to work as you want.

https://developer.mozilla.org/ru/docs/Learn/JavaScript/Asynchronous/Timeouts_and_intervals

https://stackoverflow.com/a/50357618

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.