Why Isn't time variable changing? - javascript

function getTime() {
const d = new Date();
const secs = d.getSeconds();
const mins = d.getMinutes();
const hours = d.getHours();
return {
'hours': hours,
'mins': mins,
'secs': secs
}
}
let time = getTime();
setInterval(getTime, 1000);
setInterval(() => {
console.log(`${time.hours}:${time.mins}:${time.secs}`);
}, 1000);
The time displayed doesn't change. It just continually runs, outputting the same time instead of showing a change each second...

time variable is declared only once, when script loads and stays in that state. Move it inside the interval to keep it updated.
function getTime() {
const d = new Date();
const secs = d.getSeconds();
const mins = d.getMinutes();
const hours = d.getHours();
return {
'hours': hours,
'mins': mins,
'secs': secs
}
}
setInterval(() => {
const time = getTime();
console.log(`${time.hours}:${time.mins}:${time.secs}`);
}, 1000);

You are only setting the value of time once, to the value of getTime() at that moment.
If you want the value to change, you have to set the value again every iteration.
setInterval(() => {
var time = getTime();
console.log(`${time.hours}:${time.mins}:${time.secs}`);
}, 1000);

That's because you are not updating the time variable, but just calling getTime in setInterval.
This is how it should be:
setInterval(function() {
time = getTime();
console.log(`${time.hours}:${time.mins}:${time.secs}`);
}, 1000);
Note:
If you declare your time variable as constant with cons keyword, trying to change it will throw this error:
Uncaught TypeError: Assignment to constant variable.
Demo:
function getTime() {
const d = new Date();
const secs = d.getSeconds();
const mins = d.getMinutes();
const hours = d.getHours();
return {
'hours': hours,
'mins': mins,
'secs': secs
}
}
var time = getTime();
setInterval(function() {
time = getTime();
console.log(`${time.hours}:${time.mins}:${time.secs}`);
}, 1000);

Time is not changing because you are using variable which are not getting updated.
Here are two problems
const time = getTime();//its called once and time values are const
will never change again
setInterval(getTime, 1000);//here function is getting executed but
return value is never used and never assigned to time variable which
is printed.
function getTime() {
const d = new Date();
const secs = d.getSeconds();
const mins = d.getMinutes();
const hours = d.getHours();
return {
'hours': hours,
'mins': mins,
'secs': secs
}
}
//const time = getTime();//its called once and time values are const will never change again
//setInterval(getTime, 1000);//here function is getting executed but return value is never used and never assigned to time variable which is printed.
setInterval(() => {
var time=getTime();
//getTime
console.log(`${time.hours}:${time.mins}:${time.secs}`);
}, 1000);

Related

Making a clock autorefresh using setInterval

i wanted to build a clock and my only problem here is that setInterval basically does not work. Am I missing something
const timer = document.getElementById("container")
let currentTime = new Date()
let hours = currentTime.getHours()
let minutes = currentTime.getMinutes()
let seconds = currentTime.getSeconds()
function time () {
let hoursIf = hours.toString().length==1 ? "0"+hours : hours
let minutesIf = minutes.toString().length==1 ? "0"+ minutes : minutes
let secondsIf = seconds.toString().length==1 ? "0" +seconds : seconds
timer.textContent = `${hoursIf}:${minutesIf}:${secondsIf}`
}
time()
let run = setInterval(time, 1000)
It works, trust me. The problem is the assigment in:
let hours = currentTime.getHours()
let minutes = currentTime.getMinutes()
let seconds = currentTime.getSeconds()
You're assigning time once at the start, and don't check for updated values later. If you'd put that in your time function it would work properly.
Something like this:
function time () {
let currentTime = new Date()
let hours = currentTime.getHours()
let minutes = currentTime.getMinutes()
let seconds = currentTime.getSeconds()
let hoursIf = hours.toString().length==1 ? "0"+hours : hours
let minutesIf = minutes.toString().length==1 ? "0"+ minutes : minutes
let secondsIf = seconds.toString().length==1 ? "0" +seconds : seconds
timer.textContent = `${hoursIf}:${minutesIf}:${secondsIf}`
}
time()
let run = setInterval(time, 1000)
You aren't updating your variables. You have them as globals, but never update their values, so the method "time" keeps using the same values.
let currentTime = new Date()
let hours = currentTime.getHours()
let minutes = currentTime.getMinutes()
let seconds = currentTime.getSeconds()
These should be set in your method or at least updated to current values. Otherwise you are simply re-displaying the same time every time executes.
If you put a "Console.log" in your method, I'd bet you'd see that it does run, it just doesn't update the time as you expect.

Why is clearInterval not working for this clock?

I'm trying to create a pomodoro clock, and I can't figure out why the resetClock function is going everything except clearing the interval for the clock. It is resetting the number, but the clock keeps counting down. I'd imagine I'll have this issue when trying to implement the stop clock function also. Can someone help?
var minutes = 25;
var seconds = 0;
var startSound = new Audio('./sounds/startsound.mp3')
var resetSound = new Audio('./sounds/resetclocksound.mp3')
var stopSound = new Audio('./sounds/pausesound.mp3')
var alarmSound = new Audio('/sounds//haoduken.mp3')
var minutes_interval;
var seconds_interval;
function startClock() {
startSound.play();
minutes = 24;
seconds = 59;
document.getElementById('minutes').innerHTML = minutes;
document.getElementById('seconds').innerHTML = seconds;
document.getElementById('start-button').removeEventListener('click', startClock)
var minutes_interval = setInterval(minutesTimer, 60000);
var seconds_interval = setInterval(secondsTimer, 1000);
function minutesTimer() {
minutes = minutes - 1;
document.getElementById('minutes').innerHTML = minutes;
}
function secondsTimer() {
seconds = seconds - 1;
document.getElementById('seconds').innerHTML = seconds;
if (seconds <= 0) {
seconds = 60;
}
if (seconds <= 0 && minutes <= 0) {
alarmSound.play()
clearInterval(minutes_interval);
clearInterval(seconds_interval);
}
}
}
function resetClock() {
clearInterval(seconds_interval);
clearInterval(minutes_interval)
resetSound.play();
var minutes = 25;
var seconds = 0;
document.getElementById('minutes').innerHTML = minutes;
document.getElementById('seconds').innerHTML = seconds;
document.getElementById('start-button').addEventListener('click', startClock)
}
The problem is on the lines where you start the interval:
var minutes_interval = setInterval(minutesTimer, 60000);
var seconds_interval = setInterval(secondsTimer, 1000);
the problem is simply your use of the var keyword, which creates a new local variable inside the startClock function. It does nothing to the outer (global?) variables of the same name, because those are "shadowed" by the new local variables.
As a consequence, the clearInterval calls inside resetClock are referencing the outer variables, which do not hold a timer ID.
The solution is probably very simple: just remove the var from the above two lines. You now only have one "global" minutes_interval and seconds_interval, which will be referenced by the clearInterval calls. From a quick glance, it appears that this should work OK for you, and that you only ever set these intervals up once before cancelling them. But if you wanted to use this code to set up multiple intervals simultaneously you'd have to rethink your approach.

How to implement a refresh status in Javascript?

So I'm trying to do a refresh status in which if the page was refreshed under 5 minutes, it would say "Updated Just Now," and if it was updated over 5 minutes ago, it would say, "Updated Moments Ago." Below is my Javascript:
var startTime, endTime;
function start() {
startTime = performance.now();
};
function end() {
endTime = performance.now();
var timeDiff = endTime - startTime; //in ms
// strip the ms
timeDiff /= 1000;
var seconds = Math.round(timeDiff);
if (seconds < 10) {
time = "Updated Just Now";
} else {
time = "Updated Moments Ago";
}
document.getElementById("demo").innerHTML = time;
}
window.onload = start
window.onload = end
However, it is very buggy and sometimes doesn't work at all. Any help will be appreciated.
Unless I missed something, I think You can use setTimeout. Initially set the HTML to 'Updated just now'.
const timeout = 5 * 60 * 1000
const changeText = () => {
document.getElementById("counter").innerHTML = "Updated moments ago";
}
setTimeout(changeText, timeout)
sandbox
You can simply do this instead of doing that stuff.
/* Note That 1000 is equivalent of 1 seconds */
setTimeout(function(){
document.getElementById("demo").innerHTML = "Updated Just Now";
}, 30000); /* This value is equivalent of 30 seconds */
setTimeout(function(){
document.getElementById("demo").innerHTML = "Updated Moments Ago";
}, 300000); /* This value is equivalent of 5 minutes */

Looping clock function using setInterval

I'm trying to create a function that can return a value (the user's current time in seconds) to another variable that can be used elsewhere in my code. The function returns the correct value, but I can't figure out how to make it repeat using setInterval or setTimeout.
var currenttime = clock();
function clock() {
var now = new Date();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
var time = (hour * 3600) + (minute * 60) + second;
return time;
}
console.log(currenttime)
I want the variable currenttime to be updated every second, but changing the line to
var currenttime = setInterval(clock, 1000);
returns an incorrect value. Alternatively I've also tried to make the clock function repeat,
but I'm not sure how to do this as I'm using a return statement so the function ends before it can be repeated.
Does anyone know what I'm doing wrong?
Assign to currentTime every time clock runs, but don't return the time - since this'll be in an interval, the return value is ignored:
let currentTime;
function clock() {
var now = new Date();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
currentTime = (hour * 3600) + (minute * 60) + second;
}
setInterval(clock, 1000);
setTimeout(() => console.log(currentTime), 2000);
setTimeout(() => console.log(currentTime), 6000);
This is a bit weird, though - variable assignment alone doesn't have side effects (in almost all cases). It would make more sense for whatever uses the currentTime variable to call clock to get the current number of seconds, eg:
function clock() {
var now = new Date();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
return (hour * 3600) + (minute * 60) + second;
}
document.querySelector('button').addEventListener('click', () => {
document.querySelector('div').textContent = clock();
});
<button>Get seconds</button>
<div id="time"></div>
The function called by setInterval should call clock and display the time.
setInterval(function(){ console.log(clock()); }, 1000);
setInterval return only an ID value that can be used in clearInterval(ID) to stop setInterval loop.
So, you can do that:
function clock()
{
let [h,m,s] = (new Date().toTimeString()).match(/\d{2}/g)
return (h*3600) + (m*60) + +s
}
var currenttime = clock();
setInterval(() => { currenttime = clock() }, 1000);

How can i make a page refresh in a certain time all days?

I want my page to auto-refresh everyday at 00:01.
I've this
var targetTime = new Date();
var now = targetTime.getTime();
targetTime.setHours(0, 17, 0, 0); // hour, minute, second, millisecond
var time = targetTime.getTime() - now;
window.setTimeout(function() {
window.location.reload(true);
}, time);
The problem is when it's 00:01 the website always is re-freshing.
It's probably more efficient to check what the hour and minute of the day is once a minute, like so:
setInterval(() => {
const date = new Date()
const hour = date.getHours()
const minute = date.getMinutes()
if (hour === 0 && minute === 1) window.location.reload()
}, 60000)
Ok! So i've manage to do this, and it works!
function refreshAt(hours, minutes, seconds)
{
var now = new Date(), then = new Date();
then.setHours(hours,minutes,seconds,0);
if(then.getTime()<now.getTime())
{
then.setDate(now.getDate() + 1);
}
var timeout = (then.getTime() - now.getTime());
setTimeout(function() { window.location.reload(true); }, timeout);
}
with
refreshAt(0,1,0);

Categories

Resources