I have implemented multiple countdown timer by using this jsfiddle link
I need to set timer for each products once it added to the cart, so I implemented it by using php by passing the arguments dynamically.
For the first product the timer works fine but as I add one more product to the cart the timer runs fast for both the products.
In firebug it is throwing an error TypeError: document.getElementById(...) is null and the count of error will increase continuously.
Imp: Products will be added to the cart without refreshing the page by ajax call and in ajax call function only running the timer.
Here is my timer function code with dynamic arguments passed.
<script>
var timerData = [];
function secondPassed(row) {
var seconds = timerData[row].remaining;
var minutes = Math.round((seconds - 30) / 60);
var remainingSeconds = seconds % 60;
// var time=clearInterval(timerData[row].timerId);alert(time);
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown' + row).innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(timerData[row].timerId);
document.getElementById('countdown' + row).innerHTML = "Buzz Buzz";
//$("#product_"+row).hide();
$("#add_"+row).show();
$("#1add_"+row).show();
$("#added_"+row).hide();
$("#block_"+row).hide();
$("#sale_"+row).show();
$("#1sale_"+row).show();
$.ajax({
type: "GET",
url: 'unblock.php',
data: { id:row },
success:function(data){
$("#cart-item").html(data);
$("#amount-top").html($("#total").val());
$("#item-total").html($("#carttotal").val());
}
});
} else {
seconds--;
}
timerData[row].remaining = seconds;
}
function timer(row, min) {
timerData[row] = {
remaining:min,
timerId: setInterval(function () { secondPassed(row); }, 1000)
};
var sec=timerData[row].timerId;
}
<?php
$itemid = array();
foreach ($_SESSION["cart_item"] as $item) {
$old = strtotime(date("m/d/Y h:i:s ", time()));
$new = strtotime($item['time']);
$time = $new - $old;
?>
timer(<?php echo $item['id']; ?>,<?php echo $time; ?>);
<?php } ?>
</script>
Thanks in advance.
$time = $new - $old;is there ever a chance the value will be 0 or less than 0?