The One Bad example and One Good example of setTimeOut to cause blockage in the main thread and to cope with as good solution respectively.
Hrishikesh Kannikar
Senior Software Engineer at Persistent Systems | Full Stack Web Developer | Angular | .Net | MEAN Stack
// Output:
Start
End
Inside setTimeout
(Note : for beginners considering the output would be start, inside setTimeout, and then end because 0 as timer value, this won't be the case because of the behaviour of Call stack in GEC and the Event loop with callback queue. Do check this out)
setTimeOut is one of coolest web api though, if used for the purpose it was created. One Simple, easy to understand use case -
Ex. In case we want delays in operations involving promises.
领英推荐
If the original promise resolves or rejects before the timeout :?
If the timeout expires before the original promise resolves or rejects:
Tip : The above operation could be enhanced by a small change.Instead of rejecting the original promise, generate a confirmation dialog - "Taking more time than expected. Do you want to wait?". On click of "ok", let the original promise resolve/reject on its own, otherwise on "cancel", let the new promise reject with an error. This way provides further more control.
Think if this was not implemented and the user is frustrated over the wait for longer operations, which undoubtedly seen at many places! And which is why I have brought this example into talk.
Indeed you need to do some more work to cancel the original promise like 1ex. using abortControl to stop waiting for the original promise, still it won't change the result if you don't do, as the new promise has taken the place.
While working with the RxJS Operators, there we deal with Observables which have a built-in time mechanism, “timeout(TIMEOUT_MS)”. It's relatively simple while delaying something using RxJS, where we don't have to rely on setTimeOut. But When using promises, we may require setTimeOut as described above.
Moreover, no question on best ever advantages for setTimeOut application in Debouncing & Throttling | setTimeOut wrapped with debounce function to limit the no. of requests to the server in case of continuous search input that hits api req on each input typed |?setTimeOut wrapped withThrottling function,? where a function is executed at a regular set of intervals (scrolling, resizing), regardless of how often an event is triggered.
Senior Software Engineer at Persistent Systems
1 个月Very informative
Software Engineer @ LTIMindtree
1 个月Useful tips Hrishikesh Kannikar
Senior Software Engineer at persistent systems | Salesforce Developer
1 个月Informative
Azure Data Engineer | Data Analytics | Cloud Solutions | Optimizing Data Pipelines & ETL Processes
1 个月Insightful
Experienced Data Engineer | ETL(Informatica,Snowflake) | Azure Certified (AZ-900)
1 个月Useful tips