0

I am trying to create an Alarm Clock in Angular 2, I have all the milliseconds required for the alarm to be triggered, but how do it?

Here is my Service File.

    import { Injectable } from '@angular/core';


        @Injectable()
        export class AlarmService {
           constructor() {}

           setUpAlarms(time){
             var all =  JSON.parse(localStorage.getItem('user'));
              for(var i =0; i < all.length; i++){
                var hours = all[i]['hours'];
                var eventStartTime = new Date();
                var eventEndTime = new Date(hours.replace('T',' ').replace('-','/'));
                var duration = eventEndTime.valueOf() - eventStartTime.valueOf();           
                console.log(duration);
               } 

            console.log("CAME HERE");   
              return true;

          }
 }

This is my Component TS.

ngOnInit() {
  let time = new Date().getTime()
  this.alarmService.setUpAlarms(time);
}

How do I go about it? Any help would be greatly appreciated.

Juggernaut
  • 766
  • 1
  • 10
  • 15

2 Answers2

0

If I understand this correctly, you want to call an alarm in x amount of milliseconds. You can do this using Observable.interval:

  import { Observable } from 'rxjs';

  callAlarmIn(milliseconds) {
    Observable
      .interval(1000)
      .take(milliseconds/1000)
      .finally(() => {
        console.log('ring ring ring!');
      })
      .subscribe();
   }

This will tick one time per second and will run the finally() callback once the milliseconds you passed in have passed. I don't know exactly how you want to use this but Observables are very powerful and there's lots more you can do with Observable.interval.

The .subscribe() is only added because the interval will never start until the observable has a subscriber. You can omit the .subscribe() here and return an observable that another component may subscribe to. For simplicity I left it in. I strongly recommend you look into how it works.

Also there is this countdown timer question that's more complex: Time CountDown in angular 2

Community
  • 1
  • 1
Eeks33
  • 2,245
  • 1
  • 14
  • 17
0

While @Eeks33's answer is good, here is a nice sugary, observable-free version

export default class {
  async soundAlarmIn(milliseconds: number) {
    await delay(milliseconds);
    console.log('Wake up!!!');
  }
}

function delay(milliseconds: number) {
  return new Promise(resolve => {
    setTimeout(resolve, milliseconds);
  });
}
Aluan Haddad
  • 29,886
  • 8
  • 72
  • 84