1

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.

JustCurious
  • 344
  • 5
  • 15

1 Answers1

1

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Tibebes. M
  • 6,940
  • 5
  • 15
  • 36
  • Hmm.. Strange. The events for which `distance<0`, it is saying `Expired`, but the timer is not rendered for the other events. There are multiple events btw in an ejs `for loop`. – JustCurious Oct 22 '20 at 03:47
  • It is just running `once` for the first element/event in the db. And as I said there are multiple events with some respective event_date. Updated my question.(see the index.ejs) – JustCurious Oct 22 '20 at 03:53
  • @JustCurious please see the updated answer for multiple events – Tibebes. M Oct 22 '20 at 05:38
  • Works like a charm. thank you for your time. Appreciate it. – JustCurious Oct 22 '20 at 06:43