how setTimeOut was used to achieve asynchrony in javascript?
Around 2017 , I had encountered code samples that suggested to achieve synchronous behaviour in javascript confused me. Let us consider a function “processData” which is needed to be invoked in asynchronous way. Imagine processData is doing some cpu intensive work.
validateData();
setTimeout(function () { processData();
}, 100);
validateNextData();
How delaying a task will become asynchronous?
Coming from dotnet background, I couldn’t grasp why delaying a function invocation is asynchronous. And then the problem I was dealing with grown into something else and asynchronous requirement was no longer needed for me. After a long time I will be going back to frontend development soon. So I just started to learn about event loop.
Every ui platform like client side javascript, Microsoft winforms will have a concept like event loop. This event loop will look for tasks (we can think this task as a function or method) and execute the functions one by one. The place where these functions are waiting are called as message queue. Every event will place the corresponding event handler (if it has) in the message queue when the event is triggered. So basically these tasks are all event handlers.
The setTimeout method is a timer after which finish the callback function sent as first argument will be enqueued into message queue.
Once you get the picture of eventloop and how setTimeout works, then only it is possible to understand why and how setTimeout is used for asynchrony.
processData method need to be invoked once validateData method completed. But at the same time validateNextData need not to be blocked untill processData.
The above code hooked up the processData method into the timer. Here timer is unnecessary but main purpose of setTimeout in this case is to put processData in the queue and the code will go on to execute validateNextData without waiting for processData execution. Thus we achieve the asynchronous behaviour.