Example: When it is Midnight (hr)0 : (min) 0 : (sec) 1 Change the HTML P element to "New Day" ...
This code works but requires me to refresh the page when the time is met. I use var.getMinutes() for testing purposes.
const d = new Date();
const h = d.getHours();
const m = d.getMinutes();
const s = d.getSeconds();
const day = document.querySelector('#current-day');
function addDay() {
if(m === 13) {
day.innerHTML = 'New Day';
console.log('works');
} return
}
window.setInterval(addDay(),1000);
CodePudding user response:
There are two problems in your code.
setInterval
accepts a function as the first argument, but you're giving it the return value of the function call. You should instead pass the function tosetInterval
, like so:window.setInterval(addDay, 1000);
.
Function call (when you execute a function):
addDay()
Function definition (when you describe what the function does):
function(args) {
// perform some calculations using the arguments
}
- Inside the function
addDay
, you are usingm
. Butm
will be evaluated only once. It won't update as time passes (as it should). You should evaluatem
inside the function. More importantly, you should evaluate the current date in the function. So every time the function executes, the value ford
andm
will update. (see the code snippet below)
const day = document.querySelector('#current-day');
function addDay() {
const d = new Date();
const h = d.getHours();
const m = d.getMinutes();
const s = d.getSeconds();
if (m === 13) {
day.innerHTML = 'New Day';
console.log('works');
}
}
window.setInterval(addDay, 1000);
<div id="current-day"></div>