'How does JavaScript call web APIs?
As far as I know, JavaScript's normal behavior when I call a web API just like the setTimeout 4 times:
it should call the first one then add it to a queue waiting for the call stack to be empty .. repeatedly it will do the same for all other apis .. so the second function should wait till the first executes then start to be called .. which means that it should take the second function 2 seconds or more, then it should take the third function three seconds or more ... and so on ...
what am I missing !?
Solution 1:[1]
Try to use async await and wait for each actions to be done.
const sleep = (ms) => new Promise(e => setTimeout(e, ms));
const logSeconds = async () => {
await sleep(1000);
console.log(new Date().toLocaleTimeString());
}
const main = async () => {
await logSeconds();
await logSeconds();
await logSeconds();
}
main()
Solution 2:[2]
var TimeOutOnTimeOut = () => {
setTimeout(() => {
console.log("Like this!");
TimeOutOnTimeOut();
}, 3000);
};
TimeOutOnTimeOut();
They'll all call at the same time, you could, however, call the next after the first is finished as described.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | BananZ |
Solution 2 | Shankar Ganesh Jayaraman |