I have an askGoogle
function. I'm calling it 10 times in a loop. I'd like to make it so each call of that function takes a random amount of time. So that some calls get finished first:
Done with google 0
Done with google 3
Done with google 2
Done with google 8
Done with google 1
...
However I'm not sure how to do it. I tried to simulate it with the setTimeout
method, but it seems to force the code behave synchronously, so all next calls to the askGoogle
wait until the previous call has been finished.
const https = require("https");
let i = 0;
function askGoogle() {
setTimeout(() => {
const googleRequest = https.request("https://google.com", {
method: "GET"
});
googleRequest.once("error", err => {
console.log("Something happened!");
})
googleRequest.once("response", (stream) => {
stream.on("data", x => {
});
stream.on("end", () => {
console.log("Done with google " + i);
i++;
})
})
googleRequest.end();
}, getRandomInt(0, 50_000));
}
for (let j = 0; j < 10; j++) {
askGoogle();
}
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
How do I change it to achieve an output similar to the sample one above?
Distilling your outer logic down to the essentials makes the error more obvious: It's the counter used in the output and when you increase it. Run this canonical example:
let i = 0;
function askGoogle() {
setTimeout(() => {
console.log("Done with google " + i);
i++;
}, getRandomInt(0, 500));
}
for (let j = 0; j < 10; j++) {
askGoogle();
}
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
I would suggest passing j
as an argument to the askGoogle
function and printing that.
let i = 0;
function askGoogle(j) {
setTimeout(() => {
console.log("Done with google " + j);
}, getRandomInt(0, 500));
}
for (let j = 0; j < 10; j++) {
askGoogle(j);
}
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}