I need to reload a page's content every 30 minutes (on the hour and 30 minutes past the hour). I'm thinking JavaScript for this, and I've tried the code below, but it goes into an endless loop. I'm not sure how to change it to avoid the loop.
meta tags won't help since they can't execute on a certain minute.
function refreshContent() {
var tDate = new Date();
thisHour = tDate.getHours();
thisMinute = tDate.getMinutes();
thisSecond = tDate.getSeconds();
setTimeout("refreshContent()",60000); // in milliseconds = 1 minute
if ( thisMinute == 0 || thisMinute == 30 ) {
location.reload();
}
}
refreshContent();
You'll need to set only one timer and calculate when is the next time to refresh. That way you can prevent the page from repeatedly reloading itself when the page is loaded exactly at :00 or :30.
var minute = new Date().getMinutes(),
nextRefresh = (30 - (minute % 30)) * 60 * 1000;
setTimeout( function() { location.reload(); }, nextRefresh );
30 - (minute % 30) calculates how many minutes until the next half hour and * 60 * 1000 converts that into milliseconds. After reload is triggered the timer is set to 30 minutes.
You are immediately invoking the refreshContent function when you setup setTimeout. Try setTimeout(refreshContent, 60000);
Related
I'm trying to make a game clock where each game hour are 3 real-time minutes. But I have a hard time wrapping my head around it for some reason.
I've came up with this half working bit, with a loop of 3 minutes for each hour so it's only showing full 'game hours' which I reset once above 23 to start a fresh day.
I guess I would have to update the loop to the accuracy of the game time clock?
var hours;
if (process.argv.length > 2) {
// setting the clock
hours = parseInt(process.argv.slice(2));
}
console.log(hours);
let timerId = setInterval(function() {
hours = hours + 1
if (hours > 23) {
hours = 0;
}
console.log(hours);
}, 3 * 60 * 1000);
Yes, you would have to have a much faster repeating interval, at the level of game-seconds. If one game-hour is 3 real minutes, then game time actually runs 20 times as fast as real time, and so one game-second would last 1/20 real seconds, i.e. 50 milliseconds.
const speed = 20; // how many times faster than real time
let clockDiv = document.querySelector("#clock");
let gameStartTime = 0; // game-milliseconds;
let realStartTime = Date.now(); // real milliseconds
let timerId = setInterval(function() {
let gameTime = gameStartTime + (Date.now() - realStartTime) * speed;
let sec = Math.floor(gameTime / 1000) % 60;
let min = Math.floor(gameTime / 60000) % 60;
let hour = Math.floor(gameTime / 3600000) % 24;
// output in hh:mm:ss format:
clockDiv.textContent = `${hour}:${min}:${sec}`.replace(/\b\d\b/g, "0$&");
}, 50);
<div id="clock"></div>
I'm entirely sure where your problem is, but # 3 mins real time = 1 hour game time, 1 real second = 20 game seconds. 3600 / 180 = 20. You should be able to feed the game seconds into any normal time function to get minutes/hours etc.
I'm new to JS and I'm stuck trying to figure out what's causing my countdown timer not to countdown. The user enters the time in 00:00:00 format minutes, seconds, and milliseconds. Afterwards, I convert that format to seconds to begin the process of counting down. I think the calculations is fine, but something is not causing it not to behave as it should be. I've tested and see that the code runs in terms of entering the time and showing up in the output. I see the countdown decrementing, for both seconds and milliseconds at the same time but it should go from 10:00:00 to 09:59:99.. 09:59:98... Basically seconds won't change until milliseconds reaches zero. so 09:59:00 will be 09:58:99... Please any help is greatly appreciated. I've been going at this and been stuck.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript">
var running = 0; //Glob variable for starting/pausing timer
function startPause(){
var time = document.getElementById("timeEntered").value; //Not sure if needed but I just have the time entered be converted to seconds.
var a = time.split(":");
var timeToSeconds = (+a[0]) * 60 + (+a[1]) * 60 + (+a[2]);
if(running == 0){ //If off, turn it on.
running = 1;
countDown();
document.getElementById("startPause").innerHTML = "Start/Stop";
}else{
running = 0;
document.getElementById("startPause").innerHTML = "Resume";
}
}
function countDown() {
var time = document.getElementById("timeEntered").value; //Take user input and convert 00:00:00 format to seconds.
var a = time.split(":");
if(!timeToSeconds)
var timeToSeconds = (+a[0]) * 60 + (+a[1]) * 60 + (+a[2]);
if(running == 1){ //When user clicks start it will calculate the minutes, seconds, and milliseconds.
var minutes = Math.floor(timeToSeconds / 60);
var seconds = timeToSeconds % 60;
var milli = timeToSeconds % 100;
if(minutes <= 9) { //Add leading zeroes to display countdown in 00:00:00 format.
minutes = "0" + minutes;
}
if(seconds <= 9) {
seconds = "0" + seconds;
}
if(milli <= 9) {
milli = "0" + milli;
}
timeToSeconds--; //Decrement the time entered.
console.log(timeToSeconds);
document.getElementById("output").innerHTML = minutes + ":" + seconds + ":" + milli //Display the time 00:00:00 format.
if(timeToSeconds !== -1){
setTimeout('countDown()',100);
}
if(timeToSeconds == 0){ //When time is 00:00:00 the message will show.
document.getElementById("output").innerHTML = "The time is over."
}
}
}
</script>
</head>
<body>
<h1>Countdown Timer</h1>
<div id="mainCont">
<input type="text" id="timeEntered">
<p>
<button id="startPause" onclick="startPause()">Start/Stop</button>
</p>
<div id="output">00:00:00</div>
</div>
</body>
</html>
There are a handful of problem here, so I will go over each one and show you the solution. The first problem is that the value of timeToSeconds is the same on each iteration. The reason for this is because you are getting the value from the same unchanging source, decrementing does nothing as the value is lost on the next function call. To fix this have your function take a parameter in which you pass the remaining seconds off after you modified it:
function countDown(timeToSeconds) {
...
timeToSeconds-=0.1; //Decrement the time entered.
if(timeToSeconds <= 0){ //When time is 00:00:00 the message will show.
document.getElementById("output").innerHTML = "The time is over."
return;
}
else if(timeToSeconds !== -1){
setTimeout(function(){countDown(timeToSeconds)},100);
}
Notice I only subtracted 0.1 because our setTimeout is called after 100 milliseconds (0.1 seconds). I've also switched around the checks, as before hand you would call the timer even if timeToSeconds was 0.
The next thing was you conversion to seconds was off, in your code here:
var timeToSeconds = (+a[0]) * 60 + (+a[1]) * 60 + (+a[2]);
Both minutes and seconds are calculated in the same way, a[1] is the seconds value and should not be multiplied. And a[2] is actually 10*milliseconds (1 seconds = 1000 milliseconds). That value should be divide by 100:
if(!timeToSeconds)
var timeToSeconds = (+a[0]) * 60 + (+a[1]) + (Math.floor(+a[2]/100));
The if-statement is a basic check if the value is true (being any number). In our case it can work as a "Does this value exist" check, since we are only dealing with positive numbers. And the following conversions should be:
var minutes = Math.floor(timeToSeconds / 60) % 60;
var seconds = Math.floor(timeToSeconds) % 60;
var milli = Math.floor(timeToSeconds*100) % 100;
For the most part, your values for minutes and seconds where correct. Although the reason why milli and seconds appeared the same was because you never converted milli to it's correct value, as such they will have the same value apart from the % applied.
Here is the final result
One last thing I would like to point out is that this timer will not be exact. As it takes some time between the computation and the setTimeout call. For a more accuracy value you will want to use Date.now() and find the different between the start time and the current timer. This question uses such a method to do so, which can be applied to the countdown timer in the same fashion.
I've a problem when running this script for my JavaScript countdown (using this plugin). What it should do is take the starting time, the current time and the end time and display the remaining time.
If I set these values with normal numbers in epoch time everything works just fine, but my question is: How do I set the current time and the start to be the real current one so that the countdown will be dynamic?
I've found this line: Math.round(new Date().getTime()/1000.0);
But I don't know how to make it work, considering I'm running this script at the bottom of my HTML file, before the </html> tag.
This is the script:
<script>
$('.countdown').final_countdown({
start: '[amount Of Time]',
end: '[amount Of Time]',
now: '[amount Of Time]'
});
</script>
This is how I tried to solve it, but it's not working:
//get the current time in unix timestamp seconds
var seconds = Math.round(new Date().getTime()/1000.0);
var endTime = '1388461320';
$('.countdown').final_countdown({
start: '1362139200',
end: endTime,
now: seconds
});
It sounds like you would like to count down from the current time to some fixed point in the future.
The following example counts down and displays the time remaining from now (whenever now might be) to some random time stamp within the next minute.
function startTimer(futureTimeStamp, display) {
var diff;
(function timer() {
// how many seconds are between now and when the count down should end
diff = (futureTimeStamp - Date.now() / 1000) | 0;
if (diff >= 0) {
display(diff);
setTimeout(timer, 1000);
}
}());
}
// wait for the page to load.
window.onload = function() {
var element = document.querySelector('#time'),
now = Date.now() / 1000,
// some random time within the next minute
futureTimeStamp = Math.floor(now + (Math.random() * 60));
// format the display however you wish.
function display(diff) {
var minutes = (diff / 60) | 0,
seconds = (diff % 60) | 0;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
element.innerHTML = minutes + ":" + seconds;
}
startTimer(futureTimeStamp, display);
};
<span id="time"></span>
Also Math.round(new Date().getTime()/1000.0); will give you the number of seconds since the epoch, however it may be a little disingenuous to round the number. I think you would be better served by taking the floor:
var timestamp = Math.floor(Date.now() / 1000)); is probably a better option.
In addition I am not sure why you need the start time, current time and end time. In order to find the remaining number of second you just need to know when the timer should end and the current time.
I'm trying to compare to 2 dates by hour/minutes/seconds, in order to make a script to resume a script when closed. If current time is pass closed time + interval ( currently set at 30 minutes) should execute and run the script normally, if not wait till difference timeouts to execute.
Current hour/minutes/seconds is not a must but the result should be in ms interval
Example:
interval = (30 * 60 * 1000)
close time = 15:10:53
current time = 15:15:29
close time + interval = 15:40:53
first time I check if `current time` <= `close time + interval`
then calculate `difference`
`difference` = (close time + interval = 15:40:53) - (current time = 15:15:29)
Result should be setTimeout(function(){ alert("Hello"); }, time difference);
The only way I'm thinking of doing this is calculate each difference from Hour,Minutes,Seconds and then finding out the ms for setTimeout
I tried but results were weird, not something that would count as smaller than 30min
var ONE_S = 1000 ;
var timeDiff = Math.abs(closeTime - currentTime);
var diffS = Math.round(timeDiff/ONE_S)
Use Date objects and compare timestamps like so:
var interval = 30 * 60 * 1000;
var closeTime = new Date('Wed Nov 26 2015 10:17:44 GMT-0400 (AST)');
var currentTime = new Date;
var difference = (closeTime - currentTime) + interval;
if(difference < 0) {
console.log('time has expired');
}else{
setTimeout(someFunction, difference);
}
closeTime - currentTime gets the time between timestamps in ms, which will be negative if it's past closing time. We offset closing time by 30 minutes (by adding interval). Then we just have to check if difference < 0 to know if time has expired, and if not we can wait difference milliseconds to trigger someFunction
I made this timer which display H-"hours remaining" every hours, M-"minutes remaining" every minutes, same for seconds, depending on a timestamp value.
Do you see things to improve in my script and how switch from the hours timer to the minute one and from the minute one to the seconds one without refreshing the page :
window.onload = function() {
var actual_timestamp = Math.round((new Date()).getTime() / 1000);
var time_remaining=<?php echo $vote_time_limit ?> - actual_timestamp;
var spanElt = document.getElementById('timer');
var h,m,s;
setInterval( function() {
//If time_remaining is between 24 and 1h, it decreases every hours
if(time_remaining<=86400 && time_remaining>=3600){
h=Math.floor( time_remaining / 3600 % 24);
spanElt.innerHTML="H-"+h--;
time_remaining--;
}
} , 3600000 );
setInterval( function() {
//If time_remaining is between 1h and 1min, it decreases every minutes
if(time_remaining<3600 && time_remaining>=60){
m=Math.floor( time_remaining / 60 % 60);
spanElt.innerHTML="M-"+m--;
time_remaining--;
}
} , 60000 );
setInterval( function() {
//If it is between 60sec and 0sec, it decreases every seconds
if(time_remaining<60 && time_remaining>0){
s=Math.floor( time_remaining % 60);
spanElt.innerHTML="S-"+s--;
time_remaining--;
//If time_remaining =0, it takes the value of the cycle time
}else if(time_remaining==0){
time_remaining=86400; //24h
}
} , 1000 );
};
You only need one timer and set the clock to the appropriate value.
setInterval runs as soon as it can after the required interval - if the system is busy it will run a little late and slowly drift. Better to use setTimeout—estimate the time to the next epoch and run it again about 20ms after the next whole interval.