I am trying to make the year on a webpage update on the 1st of June (i need it on this day, because it is updating the year on my birthday). The question is: Is there a better way to do it with Vanilla JS because that way i am making a request every 24 hours to see if it is the expected date.
document.addEventListener("DOMContentLoaded", function () {
const informationYear = document.getElementById('information-heading-text-year');
// update year function (check every day if its 1st of June and updates the year if true)
function updateYear() {
const birthdayDate = new Date(2013, 5, 1);
let currDate = new Date();
let years = 0;
if(currDate.getMonth() === birthdayDate.getMonth() && currDate.getDay() == birthdayDate.getDay()) {
years = currDate.getFullYear() - birthdayDate.getFullYear();
informationYear.textContent = `${years}+`;
}
}
// 1 day (86,400,000 milliseconds)
const oneDayInterval = 1200;
setInterval(updateYear, oneDayInterval);
});
What do you think will be the best solution for this problem? Is it even possible to do it without an API?
I am also open to solutions with database and a server
2
Answers
I was thinking and asked myself, why checking for the exact date each day when i can just calculate the time until that date and set the timeout with that time. So i came up with this solution:
I will definitely try to play with the solution with data attribute you suggested tho.
Not sure what you exactly mean, but assuming you want to display the current age given a birthday in some element, this may be an idea. In the snippet the birthday is derived from a data attribute on the element. It’s up to you to judge if this is actually better though.