jQuery auto refresh page scheduled on clock time - javascript

Looking for a Script that will autho refresh page on scheduled local time clock.
Twise a day. Let's say at 8AM and 8PM,
every day, OR
specific week day, cush as Mon-Fri, Mon-Wed, etc.
Notice: recently, found below code and tried this but it doesn't not work. Looking for a proper script based on above description.
setInterval(function(){
var dt = new Date();
var clock_time = dt.getHours() + ":" + dt.getMinutes();
if ( clock_time === '22:10' ) {
location.reload();
}

You have left out the time in setInterval.
You can set 2 times using || (OR) operator.
let interval; // Use clearInterval(interval) to stop the interval
let refreshDelay = 60000; // Every minute
function scheduledReload() {
let dt = new Date();
let time = dt.getHours() + ":" + dt.getMinutes();
if(time ==='08:10' || time === '22:10') {
location.reload();
}
}
interval = setInterval(scheduledReload, refreshDelay);

Related

Displaying current time in JS w/ given functions

Need to display current time in JS with the given functions.
Internet searches showed JS using Date() and Time() for gathering the info, but the date and time are not showing up in the HTML when run it.
"use strict";
var $ = function(id) { return document.getElementById(id); };
var displayCurrentTime = function() {
var now = new Date(); //use the 'now' variable in all calculations, etc.
var Date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var hours = now.getHours()+ ":" + now.getMinutes() + ":"
+ now.getSeconds();
//Ok, problem now is getting HTML to call it up?
};
var padSingleDigit = function(num) {
if (num < 10) { return "0" + num; }
else { return num; }
};
window.onload = function() {
// set initial clock display and then set interval timer to display
// new time every second. Don't store timer object because it
// won't be needed - clock will just run.
};
Instructor's instructions:
"Note that to convert the computer’s time from a 24-hour clock to a 12-hour clock, first check to see if the hours value is greater than 12. If so, subtract 12 from the hours value and set the AM/PM value to “PM”. Also, be aware that the hours value for midnight is 0.
The starter project has four functions supplied: the $ function, the start of a displayCurrentTime() function, a padSingleDigit() function that adds a leading zero to single digits, and the start of an onload event handler.
In the displayCurrentTime() function, add code that uses the Date object to determine the current hour, minute, and second. Convert these values to a 12hour clock, determine the AM/PM value, and display these values in the appropriate span tags.
Then, in the onload event handler, code a timer that calls the displayCurrentTime() function at 1 second intervals. Also, make sure that the current time shows as soon as the page loads. (some comments have been included in the starter code to guide you on where to place things)."
In order to grap an html element you first need one. So i made a tag with an id of "clock". I then set an interval, running every 1000 milis (1 second) to give me the correctly formatted time.
clock = document.getElementById("clock");
let hours, minutes, seconds;
function checkDigits(num, hours) {
if (num < 10) {
return "0" + num
} else {
if (hours) {
return num - 12
}
return num
}
}
function updateTime() {
date = new Date();
hours = checkDigits(date.getHours(), true)
minutes = checkDigits(date.getMinutes())
seconds = checkDigits(date.getSeconds())
clock.innerHTML = hours + ":" + minutes + ":" + seconds;
}
window.onload = function() {
setInterval(function() {
updateTime()
}, 1000);
}
<h1 id="clock"></h1>

JavaScript clock not showing current time on mobile devices

I got this JavaScript Code to display the current time on my website, works perfectly for desktop but it doesn't work on mobile devices
It freezes on the time when the user visits the page
Is it any way to make this possible? Something like refresh the script every sec to show the current time or any other solution?
document.getElementById("clock").innerHTML = GetTime();
function GetTime(){
var d = new Date();
var nhour = d.getHours(),nmin=d.getMinutes();
if (nmin<=9) {
nmin = "0" + nmin
}
return nhour+":"+nmin+"";
}
<span id="clock"></span>
Your help is really appreciated!
EDIT: Thanks to mdickin I realized the clock doesn't update even in desktop. So the entire code has something wrong.
Yes you could use a setInterval, which runs a function at regular intervals (in milliseconds).
function setTime()
{
document.getElementById("clock").innerHTML = GetTime();
}
setInterval(setTime,1000);
You could change the number of milliseconds to suit, depending on how accurate you want to be...but I doubt you would need to worry about being more than a second out either way.
Here's a link with more information about setInterval and setTimeout
Use setInterval to run your GetTime() function every second:
document.getElementById("clock").innerHTML = GetTime();
function GetTime(){
var d = new Date();
var nhour = d.getHours(),nmin=d.getMinutes();
if (nmin<=9) {
nmin = "0" + nmin
}
return nhour+":"+nmin+"";
}
setInterval(GetTime, 1000); // run GetTime every 1000ms
<span id="clock"></span>
Here is a simple program that I wrote in codepen to create a live JS timer. Basically all you need to do is call the function inside a setTimeout function and provide the frequency in milliseconds.
function startTimer() {
var today = new Date();
var hours = today.getHours();
var mins = today.getMinutes();
var sec = today.getSeconds();
mins = checkTime(mins);
sec = checkTime(sec);
document.getElementById('timer').innerHTML =
hours + ":" + mins + ":" + sec;
var t = setTimeout(startTimer, 100);
}
function checkTime(i) {
if (i < 10) {
i = "0" + i
};
return i;
}
<body onLoad="startTimer()">
<div id="timer"></div>
</body>
Here is the link to my codepen

Javascript countdown every day

I need to make countdown timer for every day to 21:00. Counting till live stream.
If time is less then 21:00 display the time left and if time is from 21:00-22:00
I would like to display 'streaming right now'. After 22:00 start counting till tomorrow at 21:00.
Any suggestins how to do this?
Here is what I tried so far but it doesn't work well and also if client change the time on his computer the counter will change. I need to fix that on server side so for everyone it will show the same time.
<script type="text/javascript">
$(document).ready(function(){
var curT, tarT, difT;
curT = new Date().getTime()/1000;
tarT = new Date('<?php echo (new DateTime('May 05, 2014'))->add(new DateInterval("P1D"))->format('M d, Y');?>, 21:00:00').getTime()/1000;
init();
function init(){
var d,h,m,s;
difT = tarT - curT;
function updateT(){
s = difT;
d = Math.floor(s/86400);
s -= d * 86400;
h = Math.floor(s/3600);
s -= h * 3600;
m = Math.floor(s/60);
s -= m * 60;
s = Math.floor(s);
}
function tick(){
clearTimeout(timer);
updateT();
displayT();
if(difT>0){
difT--;
timer = setTimeout(tick,1*1000);
} else {
$('.timeleft').html('Aukcija u toku...');
}
}
function displayT(){
var out;
out = h+":"+m+":"+s;
$('.timeleft').html(out);
}
var timer = setTimeout(tick,1*1000);
}
});
</script>
Since you need a combination of both scripts from above, I combined them for you: http://jsfiddle.net/69TAf/
Reads out the real time from GMT Server
Clients timezone doesn't matter
GMT Server is only pinged once at beginning (for better performance)
Added leading zeros so it looks better
Credits to edcs and Miskone!
var date;
var display = document.getElementById('time');
$(document).ready(function() {
getTime('GMT', function(time){
date = new Date(time);
});
});
setInterval(function() {
date = new Date(date.getTime() + 1000);
var currenthours = date.getHours();
var hours;
var minutes;
var seconds;
if (currenthours != 21){
if (currenthours < 21) {
hours = 20 - currenthours;
} else {
hours = 21 + (24 - currenthours);
}
minutes = 60 - date.getMinutes();
seconds = 60 - date.getSeconds();
if (minutes < 10) {
minutes = '0' + minutes;
}
if (seconds < 10) {
seconds = '0' + seconds;
}
display.innerHTML = hours + ':' + minutes + ':' +seconds;
} else {
display.innerHTML = 'LIVE NOW';
}
}, 1000);
function getTime(zone, success) {
var url = 'http://json-time.appspot.com/time.json?tz=' + zone,
ud = 'json' + (+new Date());
window[ud]= function(o){
success && success(new Date(o.datetime));
};
document.getElementsByTagName('head')[0].appendChild((function(){
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = url + '&callback=' + ud;
return s;
})());
}
And html:
<div id='time'></div>
If you don't want to ping an external server for getting the time, you can use this fiddle (not working on jsfiddle, since contains php):
http://jsfiddle.net/qQ6V3/ - I think it's even better this way.
If you need everyone to be counting down from the same time, then you'll need to grab it from a centralised time server. This code does exactly that:
function getTime(zone, success) {
var url = 'http://json-time.appspot.com/time.json?tz=' + zone,
ud = 'json' + (+new Date());
window[ud]= function(o){
success && success(new Date(o.datetime));
};
document.getElementsByTagName('head')[0].appendChild((function(){
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = url + '&callback=' + ud;
return s;
})());
}
getTime('GMT', function(time){
// This is where you do whatever you want with the time:
alert(time);
});
Source
If you use getTime() instead of grabbing the local time from the client then everyone will be in sync.
you can do something like this :
<div id='time'></div>
and the script :
var display = document.getElementById('time');
setInterval(function(){
var date = new Date();
var currenthours = date.getHours();
var hours;
var minutes;
var secondes;
if (currenthours != 21){
if (currenthours < 21)
hours = 20 - currenthours;
else hours = 21 + (24 - currenthours);
minutes = 60 - date.getMinutes();
secondes = 60 - date.getSeconds();
display.innerHTML = hours + ':' + minutes + ':' +secondes;
}
else display.innerHTML = 'LIVE NOW';
},1000);
fiddle: http://jsfiddle.net/KbM8D/
Lots of answers, one more won't hurt. :-)
I think you are best to pass the start and end of streaming to the client as a UNIX UTC time values in seconds. Then the client can turn that into a local date and count down to that. Using a network time server sounds good, but it means that everyone must use the same time server and you are reliant on the server being available.
if you're going to pass a time at all, it might as well be the start and end according to your server. You can even pass the current time from the server and calculate a time offset to apply at the client. Anyhow, the code…
<script>
var countDown = (function() {
var startStream;
var endStream;
var streamingText = 'streaming right now';
var updateElement;
// Pad single digit numbers
function pad(n) {
return (n<10?'0':'') + +n;
}
// Format a time difference as hh:mm:ss
// d0 and d1 are date objects, d0 < d1
function timeDiff(d0, d1) {
var diff = d1 - d0;
return pad(diff/3.6e6|0) + ':' + pad((diff%3.6e6)/6e4|0) + ':' + pad(diff%6e4/1000|0);
}
// start, end are UNIX UTC time values in seconds for the start and end of streaming
return function(elementId, start, end) {
var now = new Date();
var returnValue;
// By default, run again just after next full second
var delay = 1020 - now.getMilliseconds();
// turn start and end times into local Date objects
if (start) startStream = new Date(start*1000);
if (end) endStream = new Date(end*1000);
// If now is after endStream, add 1 day,
// Use UTC to avoid daylight saving adjustments
if (now > endStream) {
endStream.setUTCHours(endStream.getUTCHours() + 24);
startStream.setUTCHours(startStream.getUTCHours() + 24);
}
// Store the element to write the text to
if (elementId) updateElement = document.getElementById(elementId);
// If it's streaming time, return streaming text
if (now >= startStream && now < endStream) {
returnValue = streamingText;
// Run again after streaming end time
delay = endStream - now;
} else {
// Otherwise, count down to startStream
returnValue = timeDiff(now, startStream);
}
// Write the time left or streaming text
updateElement.innerHTML = returnValue;
// Call again when appropriate
setTimeout(countDown, delay);
};
}());
// Testing code
// Create dates for a local time of 21:00 today
var myStart = new Date();
myStart.setHours(21,0,0,0);
var myEnd = new Date()
myEnd.setHours(22,0,0,0);
// Create UNIX time values for same time as UTC
var startUTCTimeValue = myStart/1000|0
var endUTCTimeValue = myEnd/1000|0
// Run when page loads
window.onload = function() {
countDown('foo', startUTCTimeValue, endUTCTimeValue);
}
</script>
<div id="foo"></div>

Countdown Timer for every 6 hours

Just wondering, if there is any way or codes, that can set countdown timer for every 6hours, for everyday?
For example, i want to start countdown at this timing(In other words, like every 6 hours):
9am-3pm
3pm-9pm
9pm-3am
3am-9am?
I have look all over the site, and couldn't find a countdown timer like that..
Preferably in HTML and javascript/jquery.
var timer = {
started: false,
timestamp: 0
},
trigger = 15; //3pm
function timerInit(){
var hour = new Date().getHours();
if(!started && hour === trigger){ //When it's 3pm, the timer will start
startTimer(); //└─ rewrite the conditional statement
// as needed
//do whatever you want here
timer.timestamp = +new Date();
timer.started = true; //Indicates the timer has been started
}
requestAnimationFrame(timerInit); //setTimeout is not efficient
}
requestAnimationFrame(timerInit);
//This is for when the timer has ended.
function timerEnded(){
timer.started = false;
}
function startTimer(){
var d = new Date();
timePassed = new Date(timer.timestamp + 1000*60*60*6 - d);
var remaining = { //Calculate time difference
hour: timePassed.getHours(), // using timestamps
minute: timePassed.getMinutes(),
second: timePassed.getSeconds()
}
console.log(remaining);
if(timePassed > 0){
setTimeout(startTimer, 500); //Countdown
}else{
timerEnded(); //Ended
}
}
http://jsfiddle.net/DerekL/kKPcr/7/
You can use javascript's native setInterval method
E.g:
var timer = setInterval(myfunction, 21600) // 21600 seconds == 6 hours

Unix timestamp to seconds in javascript

I'm trying to do a program which executes after 15 minutes of being in the page. My problem is how to get the exact number to add on the timestamp which is stored in a cookie.
I need a function to convert seconds into timestamps or anything that can make the action execute after 15 minutes. I don't really know how much time is 1792939 which I place in the code below.
setInterval("timer()",1000);
$.cookie("tymz", time);
function timer(){
var d = new Date();
var time = d.getTime();
var x = Number($.cookie("tymz")) + 1792939;
//alert('Cookie time: ' + x + '\nTime: ' + time);
if(time > x){
alert('times up');
}else{
//alert('not yet\n' + 'times up: ' + x + '\ntime: ' + time);
}
}
How about using setTimeout(..)?
<script type="text/javascript">
function myFunc()
{
alert("I will show up 15 minutes after this pages loads!");
}
setTimeout("myFunc()",60*15*1000);
</script>
Check this: http://www.w3schools.com/js/js_timing.asp
unix timestamp are second from epoch (1/1/1970) so if you want to execute some code after 15 minutes just record the time when the page is loaded then every second calculate how many seconds are passed from page load. When the difference between current time and page load time is greater than 15*60*1000 you can execute your code.
var pageLoad = new Date().getTime();
function tick(){
var now = new Date().getTime();
if((now - pageLoad) > 15*60*1000) executeYourCode();
}
setInterval("tick()",1000);
Remeber that javascript return time in millisecond
Hope this helps
If the number is seconds since 1/1/1970 00:00:00, then you can convert '1792939' to a javascript date by multiplying by 1,000 and passing to Date:
var d = new Date(1792939 * 1000) // Thu Jan 22 1970 04:02:19
Currently it is about 1311428869 seconds since 1/1/1970. So if you have a value for seconds, then you can use setInterval to run a function 15 minutes after that:
var seconds = ?? // set somehow
var start = new Date(seconds * 1000);
var now = new Date();
var limit = 15 * 60 * 1000;
var lag = now - start + limit;
// Only set timeout if start was less than 15 minutes ago
if ( lag > 0 ) {
setTimeout( someFn, lag);
}
Provided the current time is less than 15 minutes from the start time, the function will run at approximately 15 minutes after the start time. If the system is busy when the time expires, the function should be run as soon as possible afterward (usually within a few ms, but maybe more).
works without server or cookie (and all browser after IE7)
Looks like you use jQuery, so you might as well use jQuery.now() insted
var firstVisit = localStorage['firstVisit'] = localStorage['firstVisit'] || $.now();
function myFunc(){
alert("I will show up 15 minutes after this pages loads!");
}
setTimeout(myFunc, parseInt(firstVisit) - $.now() + 1000 * 60 * 15);

Categories

Resources