Reputation: 362
I have looked here but this couldn't solve my task.
Question on hand is:
I have a date in an event.date
col in my MySQL DB which is being retrieved like this:
app.get('/', (req, res) => {
var query1='SELECT event_date,... FROM event..';
connection.query(query1, function(err,results){
if (results) res.render('index', {data: results});
});
});
What I want is to start a timer on my page which will take the diff between new Date();
and my stored date (like this)
index.ejs
<% data.some(function(d,index){ %>
<%= d.event_date %> //this prints the data here obviously
<% **How to implement the setInterval() here??** %>
<% })%>
I tried two or more noob ways but all in vain. What concept am I missing? How to achieve this?
Thanks.
Upvotes: 1
Views: 430
Reputation: 7548
Try doing something like this (countdown func. taken from this answer)
EJS Template code:
<% data1.forEach(function(d, index){ %>
<div id="countdown<%= index %>"></div>
<% }) %>
<script>
<% data1.forEach(function(d, index){ %>
CountDownTimer("<%= d.event_date %>", "countdown<%= index %>");
<% })%>
function CountDownTimer(dt, id) {
var end = new Date(dt);
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var timer;
function showRemaining() {
var now = new Date();
var distance = end - now;
if (distance < 0) {
clearInterval(timer);
document.getElementById(id).innerHTML = 'EXPIRED!';
return;
}
var days = Math.floor(distance / _day);
var hours = Math.floor((distance % _day) / _hour);
var minutes = Math.floor((distance % _hour) / _minute);
var seconds = Math.floor((distance % _minute) / _second);
document.getElementById(id).innerHTML = days + 'days ';
document.getElementById(id).innerHTML += hours + 'hrs ';
document.getElementById(id).innerHTML += minutes + 'mins ';
document.getElementById(id).innerHTML += seconds + 'secs';
}
timer = setInterval(showRemaining, 1000);
}
</script>
Here we're are querying the DB once (when rendering the page) and then client side javascript takes care of the interval based countdown updates.
Upvotes: 1