Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to make an alarm in javascript?

Tags:

javascript

Is it possible to ser a function to start in a given date and hour? How?

I thought about setTimeout, but what's the maximum time I can set?

--update

By the way, it's for a desktop application.

like image 766
The Student Avatar asked Sep 13 '25 07:09

The Student


2 Answers

I agree with JCOC611 - if you can make sure that your application does not close, then just get a Date object of when your alarm should go off and do something like this:

window.setTimeout(function() { soundAlarm() }, 
           alarmDate.getTime() - new Date().getTime());

I see no reason for this not to work, but a lot of people exalt a timer based solution where you have a short lived timer that ticks until the set time. It has the advantage that the timer function can also update a clock or a countdown. I like to write this pattern like this:

(function(targetDate) {
    if (targetDate.getTime() <= new Date().getTime()) {
        soundAlarm();
        return;
    }

    // maybe update a time display here?
    window.setTimeout(arguments.callee,1000,targetDate); // tick every second
})(alarmDate);

This is basically a function that when called with a target date to sound an alarm on, re-calls itself every second to check if the time has not elapsed yet.

like image 174
Guss Avatar answered Sep 14 '25 22:09

Guss


setTimeout(functionToCall,delayToWait)

As stated in Why does setTimeout() "break" for large millisecond delay values?, it uses a 32 bit int to store the delay so the max value allowed would be 2147483647

like image 36
Alberto Zaccagni Avatar answered Sep 14 '25 22:09

Alberto Zaccagni