我试图创建一个预订时间的购物车。剩下的时间由php计算。当用户输入所请求的页面时,时间将以秒(整数秒)执行,来自php(会话)。如果剩下3分钟,javascript会启动一个确认框并询问用户是否要重置计时器以继续购物。
显示确认框时,计时器的执行暂停。如何更改我的代码,以便计时器运行而不会通过确认框暂停?
//Starting the Counter in the document.ready-block
//remainingSeconds($_SESSION['timer']) is the time left in seconds (as int)
CountDownTimer('<?php echo remainingSeconds($_SESSION['timer']); ?>', 'reservedTime');
这是CountDownTimer函数:
// These functions are located in an external .js-file
// Found it on StackOverflow and edited it for my needs
function CountDownTimer(dt, id)
{
if(id == "kill") {
clearInterval(timer);
} else {
var _second = 1,
_minute = _second * 60,
_hour = _minute * 60;
function showRemaining() {
var time = dt--,
minutes,
seconds;
if (dt == 180) {
var extend = confirm("Reset the timer?");
if (extend) {
resetCounter();
}
}
if (dt < 0) {
clearInterval(timer);
document.getElementById(id).innerHTML = '00:00';
alert("No time left.");
//--redirect for readability removed--
return;
}
if(time > 59) {
minutes = Math.floor((time % _hour) / _minute);
seconds = Math.floor((time % _minute) / _second);
} else {
minutes = "0";
seconds = time;
}
if(minutes < 10) {minutes = "0"+minutes}
if(seconds < 10) {seconds = "0"+seconds}
document.getElementById(id).innerHTML = minutes + ":" + seconds;
}
timer = setInterval(showRemaining, 1000);
}
}
function resetCounter() {
request = $.ajax({url: "php/ajax.php?f=3"});
request.done(function (response, textStatus, jqXHR){
try {
var data = $.parseJSON(response);
CountDownTimer('0', 'kill'); // reset old counter
CountDownTimer(data.time, 'reservedTime'); // start new one
} catch(e) {
alert("ERROR ERMAGERD");
return false;
}
});
request.fail(function (jqXHR, textStatus, errorThrown){
alert("ERROR");
});
}
当计时器暂停时,它将创建一个与会话中的时间不同的时间。因此购物车可能会过期 - 但用户不会注意到它并可能丢失他的保留物品。
编辑:或者是否有更好/安全的方法将购物车计时器与输出集成到用户,这样就不会有时差?