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 >
<span >SALE ENDS</span>
<div >
<div >${makeMeTwoDigits(days)} :</div>
<div >Days</div>
</div>
<div >
<div >${makeMeTwoDigits(hours)} :</div>
<div >Hours</div>
</div>
<div >
<div >${makeMeTwoDigits(minutes)} :</div>
<div >Min</div>
</div>
<div >
<div >${makeMeTwoDigits(seconds)}</div>
<div >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
CodePudding user response:
Thats because you used prepend
, and I assume that you want to replace the content.
Try instead
countdownContent.innerHTML = "";
countdownContent.appendChild(newHTML);