Javascript / PHP timer on multiple objects / conditions

Viewed 61

I have a table which is getting it's data from that View's Controller. I need to set a timer event when a certain condition is meet, for example when youtube link have been viewed more than 30 times --> wait 2 hours --> do something

The script below finds correct cell and sets a countdown timer just as intended. The problem is that var countDownDate is counting from moment browser is refreshed.

What would be the best way to store timestamp when first condition is meet and at the same time do it for all cells? Pure JS, PHP, or combined?

$("td.my_class").each(function(index,value) { 
    // findning all cells containing views value
  
if( value > 30 ) { 

  var countDownDate = Date.parse( new Date().addHours(2) ) ;

  // 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);

  // empty div just to see if its working..
 $(something).html( hours + "h " + minutes + "m " + seconds + "s " );

  // If the count down is over, write some text
  if (distance < 0) {
    clearInterval(x);
        // do something
  }
}, 1000);

}
}); 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table style="width:100%">
    <tr>
        <th>Youtube link</th>
        <th>Youtube link views</th>
     </tr>
     <tr>
        <td>https://www.youtube.com/watch?122</td>
        <td>30</td>
     </tr>
</table>

0 Answers
Related