Package detail

d-idle

An Angular service to detect user inactivity and emit events after a configurable timeout. Ideal for session timeout, logout triggers, or idle UX behavior.

angular, idle, user inactivity, session timeout

readme

👑 Dino_Creationz

Angular Utilities • Built for Clean, Scalable Code

💙 Built by Dinoraj

d-idle npm

📦 Installation

npm install d-idle

🔗 Live Demo

Try it on StackBlitz:
👉 Open Example

📥 Import

This is a service — no module imports required.

It's provided globally via:

@Injectable({ providedIn: 'root' })
export class DIdleService { ... }

⚙️ What It Does

  • Listens for activity events: mousemove, keydown, click, scroll, touchstart
  • Emits an event when the user has been inactive for X seconds
  • Resets the countdown anytime activity is detected
  • Ideal for: logout timers, session warnings, form locking, or UX reminders

🚀 How to Use

1. Inject DIdleService in any component

constructor(private idle: DIdleService) {}

2. Subscribe to idle$ and start tracking

ngOnInit() {
  this.idle.idle$.subscribe(() => {
    console.log('User is idle');
    this.logout();
  });

  this.idle.startWatching(60); // Start with 60 seconds timeout
}

Important: Stop Watching on Destroy

ngOnDestroy() {
  this.idle.stopWatching(); // ⚠️ Required to avoid multiple subscriptions
}

🔴 If you don’t call stopWatching(), the idle timer may keep running in the background
Especially important in routed or reused components


🔧 Method Reference

startWatching(idleTimeInSeconds: number): void

  • Begins tracking user activity
  • Resets timer on any event

stopWatching(): void

  • Stops tracking and cancels idle countdown

idle$ : Observable<void>

  • Emits once the user is idle

🛠 Example Component

@Component({ standalone: true, selector: 'session-guard', template: '' })
export class SessionGuardComponent implements OnInit, OnDestroy {
  constructor(private idle: DIdleService) {}

  ngOnInit() {
    this.idle.idle$.subscribe(() => {
      alert('Session expired!');
    });

    this.idle.startWatching(120); // 2-minute inactivity
  }

  ngOnDestroy() {
    this.idle.stopWatching(); // ⚠️ Very important
  }
}

💡 Notes

  • idle$ emits only once per inactivity period. To restart detection, call startWatching() again after handling the event if needed.
  • You can re-invoke startWatching() with a new timeout at any time.
  • Internally uses rxjs, fromEvent, timer, and merge.

🛠 Compatibility

  • Angular 15+
  • Fully standalone compatible
  • No third-party dependencies

🔍 Keywords

angular idle
user idle timeout angular
angular inactivity
angular idle service
idle timer angular
angular logout after timeout
angular session timeout
idle detection angular
angular auto logout
angular idle observer

👨‍💻 Author

Dinoraj
Social: @dinoraj0413
GitHub: github.com/dinoraj0413
Company: Dino_Creationz


Buy Me A Coffee

🧪 License

MIT