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.
setIntervalaccepts 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. Butmwill be evaluated only once. It won't update as time passes (as it should). You should evaluateminside the function. More importantly, you should evaluate the current date in the function. So every time the function executes, the value fordandmwill 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>
