typescript
52 lines · 10 steps
A self-refreshing timeAgo pipe in Angular
An impure Angular pipe that renders relative timestamps and reschedules its own change detection so the label stays current.
Explained by
highlit
1import { Pipe, PipeTransform, ChangeDetectorRef, NgZone, OnDestroy } from '@angular/core';
2
3@Pipe({
4 name: 'timeAgo',
5 standalone: true,
6 pure: false,
7})
8export class TimeAgoPipe implements PipeTransform, OnDestroy {
9 private timer: ReturnType<typeof setTimeout> | null = null;
10
11 constructor(private cdr: ChangeDetectorRef, private ngZone: NgZone) {}
12
13 transform(value: Date | string | number): string {
14 this.clearTimer();
15 const then = new Date(value).getTime();
16 const seconds = Math.round((Date.now() - then) / 1000);
17
18 this.scheduleUpdate(seconds);
19 return this.format(seconds);
20 }
21
22 private format(seconds: number): string {
23 if (seconds < 5) return 'just now';
24 if (seconds < 60) return `${seconds} seconds ago`;
25 const minutes = Math.round(seconds / 60);
26 if (minutes < 60) return `${minutes} minute${minutes === 1 ? '' : 's'} ago`;
27 const hours = Math.round(minutes / 60);
28 if (hours < 24) return `${hours} hour${hours === 1 ? '' : 's'} ago`;
29 const days = Math.round(hours / 24);
30 return `${days} day${days === 1 ? '' : 's'} ago`;
31 }
32
33 private scheduleUpdate(seconds: number): void {
34 const delay = seconds < 60 ? 1000 : seconds < 3600 ? 30000 : 300000;
35 this.ngZone.runOutsideAngular(() => {
36 this.timer = setTimeout(() => {
37 this.ngZone.run(() => this.cdr.markForCheck());
38 }, delay);
39 });
40 }
41
42 private clearTimer(): void {
43 if (this.timer) {
44 clearTimeout(this.timer);
45 this.timer = null;
46 }
47 }
48
49 ngOnDestroy(): void {
50 this.clearTimer();
51 }
52}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1An impure pipe runs on every change detection cycle, so it can manage live, time-dependent output.
- 2Scheduling timers outside Angular's zone avoids triggering needless change detection until you explicitly re-enter it.
- 3Pipes that own resources like timers must clean them up in ngOnDestroy to prevent leaks.
Related explainers
typescript
import { NestFactory } from '@nestjs/core'; import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; import { ValidationPipe } from '@nestjs/common'; import { ApiProperty } from '@nestjs/swagger';
Wiring validation and Swagger docs in NestJS
validation
openapi
decorators
Intermediate
8 steps
typescript
import { Component, Input } from '@angular/core'; interface Order { id: string;
How Angular ICU plurals localize an order summary
i18n
pluralization
standalone-component
Intermediate
8 steps
typescript
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common'; import { Observable, catchError, concatMap, finalize } from 'rxjs'; import { DataSource, QueryRunner } from 'typeorm';
Wrapping requests in a transaction with NestJS
interceptors
transactions
rxjs
Advanced
7 steps
typescript
type CsvColumn<T> = { header: string; value: (row: T) => string | number | boolean | null | undefined; };
Building a type-safe CSV writer in TypeScript
generics
serialization
escaping
Intermediate
7 steps
typescript
import { parsePhoneNumberFromString, CountryCode } from 'libphonenumber-js'; export interface NormalizedPhone { e164: string;
Normalizing phone numbers to E.164 in TypeScript
validation
normalization
error-handling
Intermediate
7 steps
typescript
import { CanActivate, ExecutionContext, Injectable,
Role-based access with a NestJS guard
authorization
guards
decorators
Intermediate
6 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-self-refreshing-timeago-pipe-in-angular-explained-typescript-0410/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.