Hi everyone I'm building a countdown timer for my site but I'm having a problem when adding the code a new countdown timer is getting created every second, I think it's because I'm injecting my html inside the setInterval function, I'm sure to fix this issue if anyone can help please.
// Set the date we're counting down to
var countDownDate = new Date("Jan 5, 2023 15:37:25").getTime();
function makeMeTwoDigits(n){
return (n < 10 ? "0" : "") + n;
}
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
const countdownHTML =
`<div class="countdown-main-container">
<span class="sale-text">SALE ENDS</span>
<div class="countdown-container">
<div class="countdown-date">${makeMeTwoDigits(days)} :</div>
<div class="countdown-text">Days</div>
</div>
<div class="countdown-container">
<div class="countdown-date">${makeMeTwoDigits(hours)} :</div>
<div class="countdown-text">Hours</div>
</div>
<div class="countdown-container">
<div class="countdown-date">${makeMeTwoDigits(minutes)} :</div>
<div class="countdown-text">Min</div>
</div>
<div class="countdown-container">
<div class="countdown-date">${makeMeTwoDigits(seconds)}</div>
<div class="countdown-text">Secs</div>
</div>
</div>`;
const countdownContent = document.querySelector('.col-sm-6');
const newHTML = document.createElement('div');
newHTML.setAttribute('id', 'randb-countdownSale');
newHTML.innerHTML = countdownHTML;
countdownContent.prepend(newHTML);
}, 1000);
jQuery('.ib-text').remove();
document.querySelector('.info-bar').style.height = "52px";
document.querySelector('.oc-panel').style.paddingTop = "10px";
const coutdownStyle = `<style branchname="countdownSale">
.countdown-main-container {
flex-direction: row;
display: flex;
align-items: center;
gap: 10px;
}
.countdown-container {
display: flex;
justify-items: center;
align-items: center;
flex-wrap: wrap;
flex-direction: column;
}
.sale-text {
font-family: 'Playfair Display';
font-size: 20px;
color: #ffffff;
font-weight: 400;
padding-right: 10px;
}
.countdown-date {
font-size: 20px;
color: #fff;
}
.countdown-text {
color:#fff;
}
#colon {
padding-left: 20px;
}
</style>
`;
jQuery("header").append(coutdownStyle);
I tried removing my html from inside the setInterval function but my code then spot working
Thats because you used prepend
, and I assume that you want to replace the content.
Try instead
countdownContent.innerHTML = "";
countdownContent.appendChild(newHTML);