I know it sound stupid because javascript is single threaded but can't help thinking about a function which takes unusual amount time with no involvement from web APIs like this
console.log("start")
function apple() {
let appleCount = 10;
while (appleCount < 1000000) {
appleCount = appleCount + 10;
appleCount = appleCount * 0.0000052
}
}
apple();
console.log("end")
so is there a way to run this apple function asynchronously ... i tried running this code in browser but not getting any results... help me out..
The only way to run something that is 100% plain Javascript like your apple()
function so that it doesn't block the main thread is to run it in a different thread (in nodejs, to use a WorkerThread) or in a different process.
As you seem to know the main thread runs your Javascript in a single thread so anything that is just plain JavaScript occupies that single thread while it is running. To have it not occupy that single thread and block the event loop, you have to run it in a different thread, either a WorkerThread
or run it in another process.
One can use timing tricks such as setTimeout(apple, 100)
or setImmediate(apple)
or even Promise.resolve().then(apple)
to change WHEN the code runs (delaying when it starts), but all these timing tricks do is change when the code starts running. In all these cases, when it runs, it still blocks and occupies the main thread and blocks the event loop while its running.
FYI, there are many asynchronous operations in nodejs that are not necessarily web APIs. For example, there are asynchronous file APIs and crypto APIs that are asynchronous and non-blocking. So, your question should be modified to not refer just to web APIs, but any asynchronous API.