setinterval vs settimeout - javascript

How can run a countdown timer at 7:50 AM for 10 minutes until 8:00AM everyday. After that the shift will close. the timer will be a warning for finishing the work.
I used different flavours of setinterval and settimeout code snippets for some hours now. but i don't know how to proceed.My main question is to use setinterval or setimeout.
1) setinterval: is checking the that the time is 7:50 after every few minutes is ok?
2) settimeout: is it ok to count the seconds of the day. and then proceed with calling the function after those seconds?
This works for me
window.setInterval(function() {
var date = new Date();
if (date.getHours() === 8 && date.getMinutes() === 0) {}
}, 60000);
var now = new Date();
var millisTill10 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 10, 0, 0, 0) - now;
if (millisTill10 < 0) {
millisTill10 += 86400000;
}
setTimeout(function() {
alert("It's 10am!")
}, millisTill10);

Run a timer for every minute. Show your warning if the current time falls within your allocation. The problem with this code is that it is only accurate up to a minute - not up to the second.
And running this every second is not a good practice.
setInterval(function(){
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
//Rough estimation for the time between 7.50 and 8.00 here
if (h === 7 && m >= 50)
console.log('Warning!');
}, 1000)
Now we can do more...
We can get the above routine to kick-start a timeout function which is going to be precise in the interval. It will trigger a countdown timer at the correct time and set alarm for another 24 hours.
var starter = setInterval(function(){
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
//Rough estimation for the time between 7.50 and 8.00 here
if (h === 7 && m >= 50)
setTimeout(timer24(), 1000 * 60 * 24)
}, 1000)
function timer24(){
//Warn every 10 seconds
var countdown = setInterval(function(){
console.log('Warning!');
var d = new Date();
var h = d.getHours();
if (h == 8)
clearInterval(countdown)
}, 10)
setTimeout(timer, 1000 * 60 * 24)
}

setInterval is used to repeat a callback function with a given time, setTimeout is used to run a callback after a specific amount of time. Since you need to create a counter, you can use setInterval here.
Note: If you want to display the users every sconds in 10 minutes, you may use 1000 as the interval timing value. But if you want to show every minutes in the 10 minute duration, then using 60 * 1000 as the interval timing value is better.
setInterval(function(){
var dateNow = new Date();
if(dateNow.getHours() >= 7 &&
dateNow.getMinutes >= 50 &&
dateNow.getHours < 8)
{
// if the alert box isn't displayed yet
// display it first.
// update the display.
}else{
// if the alert box is displayed
// hide it
}
}, 1000); // or 1000 * 60 for minute based display

Related

How to modify count down timer in javascript code

is there a way to manipulate a count-down timer to change the time of the countdown to zero much faster? here is the code for the:
function CalcTimePercent(i, lastpayment, nextpayment, t, p) {
var time = nextpayment - t;
var hour = parseInt(time / 3600);
if ( hour < 1 ) hour = 0;
time = parseInt(time - hour * 3600);
if ( hour < 10 ) hour = '0'+hour;
var minutes = parseInt(time / 60);
if ( minutes < 1 ) minutes = 0;
time = parseInt(time - minutes * 60);
if ( minutes < 10 ) minutes = '0'+minutes;
var seconds = time;
if ( seconds < 10 ) seconds = '0'+seconds;
timer = hour+':'+minutes+':'+seconds;
document.getElementById('deptimer'+i).innerHTML = timer;
if(timer == "00:00:00") {
top.location.href='';
}
if(timer == "00:00:0-64") {
top.location.href='';
}
t = t + 1;
setTimeout("CalcTimePercent("+i+", "+lastpayment+", "+nextpayment+", "+t+", "+p+")",1000);
}
The easiest way I can think of is using JavaScript's Date class. You would get the time the timer would end, as well as the current time, and constantly check the difference between the two. Here is how you would do that in your case:
let timer = null;
function runTimer(time) {
clearInterval(timer);
timer = setInterval(() => {
const timer = new Date(time.getTime() - new Date().getTime()); // Get difference between now and the end time
const timerText = `${timer.getUTCHours()}h ${timer.getMinutes()}m ${timer.getSeconds()}s`; // Generate a stylised version of the text
// document.getElementById("ELEMENT_ID").textContent = timerText; // Apply the stylised text to the timer element
console.log(timerText); // Apply the stylised text to the timer element
}, 1000); // Run this every 1000ms (1 second)
}
runTimer(new Date(Date.now() + 10 * 60000)); // Start timer for 10 minutes in the future
setTimeout(() => { // Wait 5 seconds
runTimer(new Date(Date.now() + 15 * 60000)); // Update timer for 15 minutes in the future
}, 5000);
The limitation of this method include the fact that it only supports times up to 24 hours. Any time over that will loop back (A timer of 27 hours will show up as "2h 0m 0s").

Automatically load new HTML page at given time

I would like my homepage to change each day at a specific time (1pm).
The page has a 24hr countdown timer and when it reaches zero, I would like a new page to load and the timer starts again.
I understand how to make a page refresh after a particular time
<script>
setTimeout(function(){
window.location='Page2.html';
}, 5000);
</script>
But not how to make this happen at a particular time of the day (1pm).
You can try using a getting the current time on page load/refresh. Then calc the milliseconds until 1pm. And use that to set your setTimeout. I suggest using a library like moment to do time calculations.
Load moments in your html:
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.16.0/moment.min.js"></script>
In JS:
// time right now
var now = moment.now();
// set refresh hour to 1pm
var nextRefresh = moment.now().hour(13).minute(0).second(0).millisecond(0);
// check if is or after 1pm
if (now.hour >= 13) {
nextRefresh.add(1, 'days'); // add 1 day
}
setTimeout(function() {
console.log('next 1pm');
}, nextRefresh.diff(now));
And #Stoycho Trenchev is right. You will probably want to call setInterval with 86400000 ms in the setTimeout. This way, your page will refresh everyday afterwards.
You need setInterval not setTimeout and you need to calculate 24h in milliseconds :)
Here you go just a fyi JavaScript uses the browsers time so just because it's 1pm where you are it won't be 1pm where the user is.
var intervalId = window.setInterval(checkTime, 500);
function checkTime() {
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
if(h == 13 && m == 0 && s == 0) return window.location='Page2.html';
}
Ah. Something like?
<script>
function getTime() {
var date = new Date()
var time = date.getTime();
var hours = time.getHours();
var minutes = time.getMinutes();
var seconds = time.getSeconds();
var time = {'hours': hours, 'minutes': minutes, 'seconds': seconds};
}
setInterval(function() {
var time = getTime();
if (time.hours === 13 && time.minutes === 0) {
window.location = 'Page2.html';
}
}, 500);
</script>
You'll need setTimeout to set a timer and Date to calculate how long the timer needs to go until it triggers.
var now = new Date();
var millisTill10 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 10, 0, 0, 0) - now;
if (millisTill10 < 0) {
millisTill10 += 86400000; // it's after 10am, try 10am tomorrow.
}
setTimeout(function(){alert("It's 10am!")}, millisTill10);

Javascript compare 2 dates and result must be setTimeout() Method in ms

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

Javascript Time - Run a Function every Half Hour

I made this function that does two things: returns the amount of time until the next thirty minute mark, and calls the halfHour function when the timer reaches zero. If the time was 12:06:27, output would be 24:33 (mm:ss)
function checkTime() {
var time = new Date();
var mins = time.getMinutes();
mins = (60-mins) % 30;
var secs = time.getSeconds();
if (secs != 60){
secs = (60-secs) % 60;
} else {
secs = 00;
}
time = [Number(mins),Number(secs)];
if (mins == 0 && secs == 0){
halfHour();
}
return time;
}
This works, but there is a strange glitch. When the minute rolls over, it shows...
24:02
24:01
23:00
23:59
23:58
It also calls halfHour(); one minute too soon, at the false 0:00 mark in the last sequence: 1:02 1:01 0:00 0:59
How can we correct this?
Solved
Commenters dbrin and njzk2 have the solution. It's subtracting minutes and seconds from 59 instead of 60. Below is the modified working code. Sorry it's messy.
function checkTime() {
var time = new Date();
var mins = time.getMinutes();
mins = (59-mins) % 30;
var secs = time.getSeconds();
if (secs != 60){
secs = (59-secs) % 60;
} else {
secs = 00;
}
time = [Number(mins),Number(secs)];
if (mins == 0 && secs == 0){
halfHour();
}
return time;
}
Why reinvent the wheel when JavaScript has a built in setInterval(code, delay); to acheive this.
setInterval(function() {
alert("I will fire after every 2 seconds")
}, 2000);
The way you measure the time is flawed. The number of minutes and the number of seconds cannot be considered separately, as I showed in my earlier comment.
An easier way is to start by measuring the total number of seconds, and then format it:
var time = new Date();
var totalS = 60 * ((60 - time.getMinutes()) % 30) - time.getSeconds()
var secs = totalS % 60
var mins = (totalS - secs) / 60

Executing code inside setInterval function only once per few seconds

I'm working on a simple project that is HTML and Javascript; and I have a problem with my timer.
I'm calculating the seconds between two Date() objects; and every 2 seconds, I want to get a new random number. I have a setInterval that runs every 100 ms and when I get past the 2 second mark, the code inside the if statement should run.
So my question is:
How can I make sure the code execute only once per 2 seconds in an if statement that is inside a setInterval() that runs every 100 ms?
Here is the code:
var startTime = new Date();
var endTime = new Date();
var randomNumber = 0;
var gameTimer = setInterval(function(){
//calculate seconds;
var secondsPassed = Math.round( (endTime - startTime) / 1000 );
if(modulo(secondsPassed,2) == 0){
//when the "gate" is open this keep executing every 100 mili seconds.
//but i want it to execute only once every 2 seconds.
randomNumber = Math.floor(Math.random()*lanes.length);
$(lanes[randomNumber]).append(box);
}
endTime = new Date();
}, 100);
var modulo = function (n, m) {
var remain = n % m;
return Math.floor(remain >= 0 ? remain : remain + m);
};
I think you are asking for a double-interval timer.
var interval = 100, beat = 2000, ticks = 0;
var timer = setInterval(function(){
runsEvery100ms(); // ««« Code here runs every 100 ms.
if (ticks > 0 && ticks % beat === 0) {
runsEvery2000ms(); // ««« Code here runs every 2000 ms.
ticks = 0;
}
ticks += interval;
}, interval);
Demo Fiddle here.

Categories