I've success set single time to send alert. But I have problem to set multiple time. How set multiple time to send alert?
Example: I have to send alert at 14:05, 17: 35 and 19:12
<script type="text/javascript">
var alarmDate = new Date();
alarmDate.setHours(21);
alarmDate.setMinutes(47);
// set day, month, year, etc.
function setAlarm(){
var currentDate = new Date();
if (currentDate.getHours() == alarmDate.getHours() &&
currentDate.getMinutes() == alarmDate.getMinutes()
/* compare other fields at your convenience */ ) {
alert('Alarm triggered at ' + currentDate);
// better use something better than alert for that?
}
}
setInterval(setAlarm,1000)
</script>
Use setTimeout instead. There is no reason to call a piece of code to cehck what time it is every single second. Just wait until the time when you want to execute something.
// Set your alarm date to whatever you require
var alarmDate = new Date();
alarmDate.setSeconds(alarmDate.getSeconds() + 5);
setAlarm(alarmDate, function(){
alert('Alarm triggered at ' + new Date());
});
var alarmDate2 = new Date();
alarmDate2.setSeconds(alarmDate2.getSeconds() + 10);
setAlarm(alarmDate2, function(){
alert('Alarm triggered at ' + new Date());
});
function setAlarm(date, callback){
// How much time from now until the alarmDate
var timeUntilAlarm = date - new Date();
// Wait until the alarm date, then do stuff.
setTimeout(callback, timeUntilAlarm);
}
Related
I have an event_start time and I want to run a script 10 seconds after that event start but can't figure out how to trigger the script.
const date = Date().toString();
const currentDateParse = Date.parse(date);
const trigger = Date.parse(startTime) + 1000 * 10
Then this is how I'm attempting to trigger the script but it's not working. How do I start my function when the currentDateParse is equal to trigger. Or, put more simply, 10 seconds after the event starts.
if (currentDateParse = trigger)
<function code underneath works already>
Calculate the time difference between now and when you want to trigger the script, and use setTimeout() to call it then.
const timediff = trigger - new Date().getTime();
setTimeout(function() {
// do what you want
}, timediff);
Try this (explanations below):
let startTime = "18:00";
let currentTime = new Date();
let target = new Date().parse(startTime);
let timeout = target - currentTime + 1000 * 10; // how long should it wait till the functions is executed
function runTenSecAfterEvent() {
// do something here
}
setTimeout(runTenSecAfterEvent, timeout);
Explanations
After you calculated target (the start time) and currentTime, you need to know the time difference between them (timeout), so target minus currentTime. After that, you add the 10000ms.
And then you define the function which will be executed 10 seconds after the event occurred (runTenSecAfterEvent()).
Finally, you create a timeout.
I want to make a banner in html in which images changes according to the day time i.e. i want to display one image between 7pm to 6am and other image during other time. After searching the wen i found out a website which does the same thing. In this the image changes according to the time of the system but i want to change the picture according to the world time zone. For eg. i wanted the image to change according to the timezone of say, Japan.
Here is the JS code:
function pixTimeChange() {
var t=new Date();
var h = t.getHours();
var r1="obanner1.jpg";
var r2="poolside3.png";
var el=document.getElementById('myimage');
// See the time below. Note: The time is in 24 hour format.
// In the example here, "7" = 7 AM; "17" =5PM.
el.src = (h>=7 && h<16) ? r1 : r2;
}
// Multiple onload function created by: Simon Willison
// http://simonwillison.net/2004/May/26/addLoadEvent/
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(function() {
pixTimeChange();
});
I've limited knowledge of Javascript and jQuery and need help in this making changes in this script.
Sorry if this question is out of scope of SO.
Check out this question for getting the timezone.
Then with JQuery you can set the src parameter for your image, like this:
if (userIsInJapan) {
$("#YourImgID").attr("src", r1);
}else{
$("#YourImgID").attr("src", r2);
}
EDIT:
I found some more details on how to check the timezone in this thread
I made this little example to show you how to use it
<script>
function calcTime(city, offset) {
// create Date object for current location
var d = new Date();
// convert to msec
// subtract local time zone offset
// get UTC time in msec
var utc = d.getTime() - (d.getTimezoneOffset() * 60000);
// create new Date object for different city
// using supplied offset
var nd = new Date(utc + (3600000*offset));
// return time as a string
return "The local time for "+ city +" is "+ nd.toLocaleString();
}
// Refresh the timer every 250 milliseconds
setInterval(function(){
$("#timeLabel").text(calcTime('Japan', '+6'));
}, 250)
</script>
<label id="timeLabel"></label>
What I would like is a timer in Javascript that goes off once a day at 2:00AM and when the timer went off there would be a alert. I'm just not sure how to do that.
P.S. I'm terrible at Javascript so if you could could you leave the whole script not just what to do :)
This should work.
function alarm() {
alert('my alert message');
setAlarm();
}
function setAlarm() {
var date = new Date(Date.now());
var alarmTime = new Date(date.getYear(), date.getMonth(), date.getDate(), 2);
if (date.getHours() >= 2) {
alarmTime.setDate(date.getDate() + 1);
}
setTimeout(alarm, alarmTime.valueOf() - Date.now());
}
setAlarm();
For a javascript web page to put up a prompt at a particular time in the future, you will have to leave a browser running with that page being displayed. Javascript from web pages in a browser only runs in pages that are currently open in the browser. If that's really what you want to do, then you can do so like this:
// make it so this code executes when your web page first runs
// you can put this right before the </body> tag
<script>
function scheduleAlert(msg, hr) {
// calc time remaining until the next 2am
// get current time
var now = new Date();
// create time at the desired hr
var then = new Date(now);
then.setHours(hr);
then.setMinutes(0);
then.setSeconds(0);
then.setMilliseconds(0);
// correct for time after the hr where we need to go to next day
if (now.getHours() >= hr) {
then = new Date(then.getTime() + (24 * 3600 * 1000)); // add one day
}
// set timer to fire the amount of time until the hr
setTimeout(function() {
alert(msg);
// set it again for the next day
scheduleAlert(msg, hr);
}, then - now);
}
// schedule the first one
scheduleAlert("It's 2am.", 2);
</script>
I'm attempting to allow a user to set an alarm from the client and pass it to the server. The server then has a setTimeout that counts down and when time runs out, executes the function.
This first part is working fine, however, I need the the ability to clear that same timeout, should the client decide to cancel that particular alarm.
Note: I've been storing various data using Redis, so that is available.
var client = redis.createClient();
io.set("store", new sio.RedisStore);
io.sockets.on('connection', function (socket) {
socket.on('alarm:config', function(list, date, time, bool) {
if (bool) {
var now = new Date().getTime();
var year = date[0],
month = date[1] - 1,
day = date[2];
var hour = time[0],
minutes = time[1];
var alarm = new Date(year, month, day, hour, minutes);
var countdown = alarm - now;
var myAlarm = setTimeout(function() {
// do stuff...
}, ( countdown ) );
} else {
clearTimeout(myAlarm);
}
});
});
The approach I have in mind is that I would use the boolean value to determine if the user is setting or canceling that particular alarm. I realize that setting a local variable "myAlarm" will not work, I just put it there to convey the idea.
I am trying to figure out a way to store a reference to that exact timeout so that the next time the "alarm:config" socket event is triggered with a false boolean value, it can cancel the timeout that was set earlier.
It might be another question all together, but how does an application like Google Calendar store a date and time and then know exactly when to trigger it as well as offer the ability to cancel it? This would essentially be the same idea.
UPDATE: I have it working using the following solution. I am open to a more elegant solution.
socket.on('alarm:config', function(list, date, time, bool) {
var alarmName = "timer:" + list;
if (bool) {
client.hset(alarmName, "status", true);
var now = new Date().getTime();
var year = date[0],
month = date[1] - 1,
day = date[2];
var hour = time[0],
minutes = time[1];
var alarm = new Date(year, month, day, hour, minutes);
var countdown = alarm - now;
setTimeout(function() {
client.hget(alarmName, "status", function(err, bool) {
if(bool == 'true') {
// do stuff...
} else {
console.log("This alarm has been canceled.");
}
});
}, ( countdown ) );
} else {
console.log('canceling alarm');
client.hset(alarmName, "status", false);
}
});
Depending on how large of an application you're building, there are a couple of options.
Processing Queue
You could restructure your application to use a job queue instead of simply setting timers. This has an advantage that you can split it in the future into multiple processes, but it does complicate the handling a bit.
A library like Kue uses just Redis and allows you to do a delayed put to set events in the future.
Going from the Kue readme:
var kue = require('kue')
, jobs = kue.createQueue();
// Create delayed job (need to store email.id in redis as well)
var email = jobs.create('email', {
title: 'Account renewal required',
to: 'tj#learnboost.com',
template: 'renewal-email'
}).delay(minute).save();
// Process job
jobs.process('email', function(job, done){
email(job.data.to, done);
});
// Cancel job
email.remove(function(err){
if (err) throw err;
console.log('removed completed job #%d', job.id);
});
Storing Reference to Timeout
This is much less robust, but could allow you to do it very simply. It leaves global variables floating around, and has no recovery if the process crashes.
Basically, you store the timer in a global variable and cancel it based on the job id.
var myAlarms = {}
socket.on('alarm:config', function(list, date, time, bool) {
var alarmName = "timer:" + list;
if (bool) {
myAlarms[alarmName] = setTimeout(function() {
// do stuff...
}, countdown);
} else {
clearTimeout(myAlarms[alarmName]);
}
}
Note: None of this code has been tested and it likely contains errors.
This question already has answers here:
How to measure time taken by a function to execute
(30 answers)
Closed 2 years ago.
How would I measure the time it takes for a script to run from start to finish?
start-timing
//CODE
end-timing
EDIT: in January 2011, this was the best available solution. Other solutions (such as performance.now() should be preferred now.
var start = new Date();
// CODE
var time = new Date() - start;
// time is the number of milliseconds it taken to execute the script
You may also want to wrap that in a function:
function time_my_script(script) {
var start = new Date();
script();
return new Date() - start;
}
// call it like this:
time = time_my_script(function() {
// CODE
});
// or just like this:
time = time_my_script(func);
If you are trying to profile your code, you may want to try the Firebug extension, which includes a javascript profiler. It has a great user interface for profiling, but it also can be done programmatically with its console api :
console.time('timer1');
// CODE
console.timeEnd('timer1'); // this prints times on the console
console.profile('profile1');
// CODE
console.profileEnd('profile1'); // this prints usual profiling informations, per function, etc.
Use performance.now() instead of new Date(). This provides a more accurate and better result. See this answer https://stackoverflow.com/a/15641427/730000
Use the User Timing api
For example:
in the beginning of the JS file write: performance.mark("start-script")
at the end of the JS file write: performance.mark("end-script")
then you can measure it too:
performance.measure("total-script-execution-time", "start-script", "end-script");
This will give you the time it takes to run the entire script execution.
Here is a quick function to work like a stopwatch
var Timer = function(id){
var self = this;
self.id = id;
var _times = [];
self.start = function(){
var time = performance.now();
console.log('[' + id + '] Start');
_times.push(time);
}
self.lap = function(time){
time = time ? time: performance.now();
console.log('[' + id + '] Lap ' + time - _times[_times.length - 1]);
_times.push(time);
}
self.stop = function(){
var time = performance.now();
if(_times.length > 1){
self.lap(time);
}
console.log('[' + id + '] Stop ' + (time - _times[0]));
_times = [];
}
}
// called with
var timer = new Timer('process label');
timer.start(); // logs => '[process label] Start'
// ... code ...
timer.lap(); // logs => '[process label] Lap ' + lap_time
// ... code ...
timer.stop(); // logs => '[process label] Stop ' + start_stop_diff