Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fire event at a certain time of the day

Is it possible with javascript (jQuery solutions are fine too) to fire an event/call a function at certain times of the day e.g.

call myFunctionA at 10:00

call myFunctionB at 14:00 etc..

Thanks

Mark

like image 202
ca8msm Avatar asked Jul 28 '11 08:07

ca8msm


2 Answers

  • Get current time
  • Get in milliseconds, the time difference between next execution time minus current time
  • Settimeout with result millisecons
like image 119
hungryMind Avatar answered Oct 21 '22 02:10

hungryMind


 /**
             * This Method executes a function certain time of the day
             * @param {type} time of execution in ms
             * @param {type} func function to execute
             * @returns {Boolean} true if the time is valid false if not
             */
            function executeAt(time, func){
                var currentTime = new Date().getTime();
                if(currentTime>time){
                    console.error("Time is in the Past");
                    return false;
                }
                setTimeout(func, time-currentTime);
                return true;
            }

            $(document).ready(function() {
                executeAt(new Date().setTime(new Date().getTime()+2000), function(){alert("IT WORKS");});
            });
like image 28
Stefan Höltker Avatar answered Oct 21 '22 02:10

Stefan Höltker