Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When and why to use a 'tick' in Angular 2?

Tags:

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.

like image 942
duke636 Avatar asked Jan 15 '17 09:01

duke636


People also ask

What does tick do in Angular?

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.

What is fakeAsync and tick?

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.

What is tick in browser?

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.

What is tick method in Javascript?

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.


2 Answers

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.

like image 73
Günter Zöchbauer Avatar answered Sep 28 '22 13:09

Günter Zöchbauer


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.

like image 31
Ced Avatar answered Sep 28 '22 15:09

Ced