Angular 2 equivalent for $timeout Angular 2 equivalent for $timeout javascript javascript

Angular 2 equivalent for $timeout


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);