我已经实现了多个倒计时定时器使用这个jsfiddle链接
我需要为添加到购物车中的每个产品设置计时器,因此我使用php动态传递参数来实现它。
对于第一个产品,计时器工作正常,但当我向购物车中添加另一个产品时,计时器对两个产品都运行得很快。
在firebug中抛出一个错误TypeError: document.getElementById(…)is null错误计数将不断增加。
Imp:通过ajax调用将产品添加到购物车中而不刷新页面,并且在ajax调用函数中只运行计时器。
这是我的计时器函数代码与动态参数传递。
<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>
一开始没发现有什么问题。但我注意到它似乎从分变成了秒。我在这里测试了它:http://jsfiddle.net/Twisty/joocqakz/
JQuery
var timerData = [];
function secondPassed(row) {
var seconds = timerData[row].remaining;
var minutes = Math.round((seconds - 30) / 60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
$("#countdown" + row).html(minutes + ":" + remainingSeconds);
if (seconds === 0) {
clearInterval(timerData[row].timerId);
$("#countdown" + row).html("Buzz Buzz");
$("#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, sec) {
timerData[row] = {
remaining: sec,
timerId: setInterval(function () {
secondPassed(row);
}, 1000)
};
var sec = timerData[row].timerId;
}
/*
<? php
foreach($_SESSION["cart_item"] as $item) {
$old = strtotime(date("m/d/Y h:i:s ", time()));
$new = strtotime($item['time']);
$time = $new - $old;
echo "timer({$item['id']}, $time);'r'n";
}
?>
*/
timer(1,120);
timer(2,240);
timer(3,360);