Making a clock autorefresh using setInterval - javascript

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.

Related

I work on digital clock project with Javascript and I have this issue, I want to call function in every 1 second but, setinterval doesnt work

here is my javascript code I didnt include HTML file because everything is simple.
time is displayed on webpage but seconds doesn't work
const hour = document.querySelector(".hour");
const minute = document.querySelector(".minute");
const seconds = document.querySelector(".seconds");
const timeZone = document.querySelector(".timeZone");
const date = new Date();
setInterval(setTime, 1000);
function setTime() {
hour.innerHTML = date.getHours() + " : ";
minute.innerHTML = date.getMinutes() + " : ";
seconds.innerHTML = date.getSeconds();
}
setTime();
As the comments mentioned, you need to move your date object into your interval function.
Otherwise when you instantiate the date object, it'll be static and the seconds wont increase.
Here is a snippet of it working.
const hour = document.querySelector(".hour");
const minute = document.querySelector(".minute");
const seconds = document.querySelector(".seconds");
const timeZone = document.querySelector(".timeZone");
debugger
setInterval(setTime, 1000);
function setTime() {
let date = new Date();
hour.innerHTML = date.getHours() + " : ";
minute.innerHTML = date.getMinutes() + " : ";
seconds.innerHTML = date.getSeconds();
}
setTime()
<span class="hour"></span>
<span class="minute"></span>
<span class="seconds"></span>
<span class="timeZone"></span>

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.

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);

Get elapsed time in Javascript between two timestamps

I have a method which takes a while to execute and I want to calculate how much take the execution of method:
var start = Date.now();
execute();
var final = Date.now();
var diff = final - start;
var seconds = diff / 1000;
var minutes = 0;
var hours = 0;
while(seconds >= 60)
{
minutes++;
seconds = Math.round(seconds/60);
}
while(minutes >= 60) {
hours++;
minutes = Math.round(minutes/60);
}
But I don't get correct information for minutes and seconds. Where is my mistake ?
The method takes somewhere 1 minute and few seconds, but in log shows only 20-40 seconds..
startTime = Date.now();
execute();
endTime = Date.now();
totalSeconds = (endTime -startTime)/1000
hours = Math.floor(totalSeconds/3600)
minutes = Math.floor((totalSeconds%3600)/60)
seconds = Math.floor((totalSeconds%3600)%60)
console.log(hours, minutes, seconds)
In your code, instead of dividing seconds by 60, you should subtract it. If your total time was 300 secs, in first loop, you will have seconds updated to 5 while minutes will be updated to 1.

Why Isn't time variable changing?

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);

Categories

Resources