I have seen the following is used in an Angular 2 component class:
setTimeout(()=>{}, 0);
That means, an empty function is called after 0 seconds. I know this is related to Javascript event model, but do not understand it completely.
Please explain when and why this is done in Angular 2, using a small real world example with some code snippet.
The tick() option is a flag called processNewMacroTasksSynchronously , which determines whether or not to invoke new macroTasks. If you provide a tickOptions object, but do not specify a processNewMacroTasksSynchronously property ( tick(100, {}) ), then processNewMacroTasksSynchronously defaults to true.
fakeAsynclink Wraps a function to be executed in the fakeAsync zone: Microtasks are manually executed by calling flushMicrotasks() . Timers are synchronous; tick() simulates the asynchronous passage of time.
1) A tick is just adding a task (execution of a function) into the browsers event queue, for delayed (async) execution instead of executing it synchronously. 2) To allow the browser to execute pending tasks in the event queue before executing the new code.
javascript tick marks javascript by Intra on Feb 22 2022 Donate Comment. Tip Intra 1 GREPCC. /* Template Literals/Strings are enclosed by backticks (``) rather than quotes. They allow expressions to be embedded within ${expression} placeholders. These expressions can be passed to a function.
setTimeout(()=>{}, 0);
Causes Angular to run change detection for the whole application, like ApplicationRef.tick
zone.js patches async APIs (addEventHandler
, setTimeout
, ...) and runs change detection after a callback was completed.
I'll add on the answer of Gunter as it is small at the moment.
He says :
setTimeout(()=>{}, 0);
Causes Angular to run change detection for the whole application
This is because the setTimeout
method has been monkey patched to be intercepted by angular which upon interception triggers change detection. In other words everytime setTimeout
is called a change detection happens.
this could be done like this:
const temp = window.setTimeout; window.setTimeout = (...args) => { temp(...args) angular.triggerChangeDetection(); // or w.e they use }
So the 0 is to make the change detection happen immediately and the empty function is because we don't want to do anything.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With