Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 equivalent for $timeout

I have to use (large amounts of) existing code in an Angular 2 environment. That code makes extensive use of the $timeout service from AngularJS 1.x. As opposed to various other AngularJS 1.x services that are used in the code, I am having a hard time finding a information about an Angular 2 equivalent for the $timeout service.

The Angular docs do not seem to contain any mention of a service with timeout-something in its name. The article Upgrading from AngularJS does mention the scenario I am facing:

Maybe you want access to AngularJS's built-in services like $location or $timeout.

Unfortunately, the article does not actually explain how to access those particular services, as the subsequent example HeroesService assumes a service without any dependencies supplied by AngularJS 1.x.

Articles such as this one suggest using the native setTimeout function does not live up to the capabilities of the $timeout services, either.

How can I reproduce the $timeout functionality in the Angular 2 environment?

EDIT: As has been noted in the answers, the drawbacks of the native setTimeout function are not relevant when using Angular 2. In that case, if I had the full $q from AngularJS 1.x, I could replicate the $timeout function roughly like this:

function $timeout(fn, delay) {     var result = $q.defer();     setTimeout(function () {         $q.when(fn()).then(function (v) {             result.resolve(v);         });     }, delay);     return result.promise; } 
like image 229
O. R. Mapper Avatar asked Aug 16 '17 13:08

O. R. Mapper


People also ask

What does $timeout Do angular?

$timeout in AngularJs is similar to the window. setTimeout function in JavaScript. Usage of the $timeout service allows the developer to set some time delay to execute the methods and functions as per the requirement.

What can we use instead of setTimeout in angular?

Initialize the array to empty array. So, the *ngFor will not throw any errors. Instead of using setTimeout use the option 1 mentioned by JeffryHouser.

What is the difference between $timeout and setTimeout?

setTimeout in order to display an alert message after a timeout of at least 2000 milliseconds. Angular $timeout is a wrapper written for window. setTimeout in form of a try catch block which throws exceptions via $exceptionHandler service. $timeout accepts the function to be delayed, delay time, a boolean to invoke $.

Can I use setTimeout in angular?

We can use the setTimeout() function for various reasons. It is best to allow Angular to run change detection once, between the actions that we would otherwise perform synchronously.

Is there an angular 2 equivalent of the $timeout service?

As opposed to various other AngularJS 1.x services that are used in the code, I am having a hard time finding a information about an Angular 2 equivalent for the $timeout service. The Angular docs do not seem to contain any mention of a service with timeout -something in its name.

Why do we use setTimeout() function in angular?

We can use the setTimeout () function for various reasons. It is best to allow Angular to run change detection once, between the actions that we would otherwise perform synchronously. setTimeout () is a native JavaScript function that sets a timer to execute a callback function, calling the function once the timer is done.

How to use time picker in Angular 2?

Here are some Angular 2 Time Picker Examples that might help you find the one your looking for quickly. 1. NG2 UI Datetime Picker Datetime picker converts input field into datetime selector by simply adding “ngui-datetime-picker” as an attribute. ngui is a collection of quality Angular2 directives.

How do I pick the time in NG2?

NG2 UI Datetime Picker Datetime picker converts input field into datetime selector by simply adding “ngui-datetime-picker” as an attribute. ngui is a collection of quality Angular2 directives. To make ngui available to your project, you need to install a npm package “@ngui/ngui”. 2. NG2 Bootstrap Time Picker


1 Answers

Use setTimeout native function. There is no need to use special services in Angular anymore. This is due to the introduction of zones, specifically NgZone.

Articles such as this one suggest using the native setTimeout function does not live up to the capabilities of the $timeout services, either.

Why makes you say so? The main task of $timeout service was to start digest after the delayed function is executed. You can see it from the sources:

function $TimeoutProvider() {   this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',     function($rootScope,   $browser,   $q,   $$q,   $exceptionHandler) {          timeoutId = $browser.defer(function() {           try {             deferred.resolve(fn.apply(null, args));           } catch (e) {           ...            if (!skipApply) $rootScope.$apply();  <-------------------- here         }, delay); 

In Angular zone.js intercepts all async operations and starts change detection in Angular which is kind of enhanced version of digest.

If you need to replicate the $timeout, you can roughly do it like this:

function $timeout(fn, delay, ...args) {   let timeoutId;    $timeout.cancel = $timeout.cancel || function (promise) {     if (promise && promise.$$timeoutId in $timeout.promises) {       $timeout.promises[promise.$$timeoutId][1]('canceled');       delete $timeout.promises[promise.$$timeoutId];       return clearTimeout(promise.$$timeoutId);     }     return false;   };    $timeout.promises = $timeout.promises || {};    const promise = new Promise((resolve, reject) => {     timeoutId = setTimeout(function () {       try {         resolve(fn.apply(null, args));       } catch (e) {         reject(e);       } finally {         delete $timeout.promises[promise.$$timeoutId];       }     }, delay);      $timeout.promises[timeoutId] = [resolve, reject];   });    promise.$$timeoutId = timeoutId;    return promise; }  // some basic testing  $timeout((v) => {   console.log('a', v); }, 2000, 7);  const promise = $timeout(() => {   console.log('b'); }, 3000);  promise.catch((reason) => {   console.log(reason); });  $timeout.cancel(promise); 
like image 165
Max Koretskyi Avatar answered Sep 17 '22 09:09

Max Koretskyi