setTimeout/$timeout in Angular 2

10/12/16 Update:

Based on this commit, importing Wrapper to use timeout is no longer required. Ex: use setTimeout and setInterval directly:

let timeoutId = setTimeout(() => {  
  console.log('hello');
}, 2000);

clearTimeout(timeoutId);

let intervalId = setInterval(() => {  
  console.log('hello');
}, 2000);

clearInterval(intervalId);

more examples from official repo


Old post:

It took me a while to find out how to do setTimeout in Angular 2, and it turns out to be quite different from Angular 1. Here's the declaration file from out the source:

export declare class TimerWrapper {  
    static setTimeout(fn: (...args: any[]) => void, millis: number): number;
    static clearTimeout(id: number): void;
    static setInterval(fn: (...args: any[]) => void, millis: number): number;
    static clearInterval(id: number): void;
}

Some examples:

import {TimerWrapper} from '@angular/core/src/facade/async';

TimerWrapper.setTimeout(() => {  
  console.log('hello');
}, 2000);
import {TimerWrapper} from '@angular/core/src/facade/async';

TimerWrapper.setInterval(() => {  
  console.log('hello');
}, 2000)

more examples from official repo

comments powered by Disqus