I'm working on a timer using Express.js and EJS. I'm trying to update the html dynamically but i don't get anything displayed. But i get the console.log in my cli.
<div id="countdown"> <% setInterval(function(){ %> <% var now = new Date().getTime(); %> <% var distance = expiration - now; %> <% var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); %> <% var seconds = Math.floor((distance % (1000 * 60)) / 1000); %> <% if (distance > 0 ) { %> <% console.log(minutes + ':' + seconds) %> <p>This isn't showing</p> <% } else { %> <% console.log('expired') %> <p>This isn't showing</p> <% }; %> <% }, 1000); %> </div>
CLI Am i missing something obvious?
I have other dynamic tags as <h2>Send <%= displayAmount %> to:</h2>
but they aren't working inside the conditional.
The problem is that the JavaScript keeps running, as you have programmed it to do, but the page is not re-rendering, because it is only told to render once.
You would have to write another JavaScript function that will re-render the DOM every iteration.
Something like:
let myDiv = document.getElementById('countdown');
// Delete previously added elements
while (myDiv.firstChild) {
myDiv.removeChild(myDiv.firstChild);
}
// Create a <p>
let p = document.createElement('p');
// Create your text
let text = document.createTextNode(`${minutes}:${seconds}`);
// OR:
let text = document.createTextNode('Expired');
// Append the text to <p>
p.appendChild(text);
// Append the <p> to div
myDiv.appendChild(p);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.