Reputation: 308
So I am trying to have a countdown for each value from a database. The value is in seconds and i am wanting to countdown from (let's say 100) to 0 and then display Finished
However, when I tried this my results got all muddled up and were not counting down in intervals of 1 second. If there were 3 results then it counted down in intervals of 3. I apologise in advance for my lack of knowledge regarding this.
This is my code for it all
<?php
$curtime = date("Y-m-d h:i:s");
$curtime = strtotime("$curtime UTC");
if (logged_in() === true){
$results = $dbc->query($sql);
while ($attacks = mysqli_fetch_array($results)){
$attime = $attacks['date'] - ($attacks['length'] + $curtime);
?>
<tr>
<td class="text-left"><?php echo $attacks['attack_ip'];?></td>
<td class="text-left"><?php echo $attacks['port'];?></td>
<td class="text-left"><?php echo $attacks['method'];?></td>
//////This is where the countdown is//////
<td id="<?php echo $attacks['attack_id'];?>" class="text-left"><?php echo $attime;?></td>
<td><button type="button" class="btn btn-effect-ripple btn-square btn-danger">Stop</button></td>
</tr>
<script type="text/javascript">
var sec = <?php echo $attime;?>;
var timer = setInterval(function() {
$('td#<?php echo $attacks['attack_id'];?>').text(sec--);
if (sec == -1) {
$('td#<?php echo $attacks['attack_id'];?>');
clearInterval(timer);
}
if (sec == -1) {
$('td#<?php echo $attacks['attack_id'];?>').html("<b>Finished</b>");
clearInterval(timer);
}
}, 1000);
</script>
<?php
} //End WHILE
}//END IF
?>
Upvotes: 1
Views: 132
Reputation: 171669
First thing I would suggest is not coupling php code with javascript. It makes it much harder to read and harder to maintain.
This can all be done by using a common class on the common elements. As for the interval times we can add those directly to the elements using data-
attributes
HTML
<td class="text-left my-timer" data-time="<?php echo $attime;?>"><?php echo $attime;?></td>
JS
$(function(){
// loop over each element to activate
$('td.my-timer').each(function(){
// "this" inside "each" is current element
var $elem = $(this),
// get the time value stored in data-time attribute
sec = +$elem.data('time');
// instance specific interval
var timer = setInterval(function() {
sec--;
var html = sec >= 0 ? sec : "<b>Finished</b>";
$elem.html(html);
if( sec === 0){
clearInterval(timer);
}
},1000);
});
});
JS is now separated from server code and can be placed in same file or external js file
Upvotes: 1