我有一个运行计时器倒计时的Javascript代码,它将在数据库中每秒更新一次计数器。我使用AJAX运行脚本,更新数据库并从数据库获取数据(计数器-秒),以将其回显到UI。但是,一旦刷新页面和/或转到网站上的其他页面,该脚本将停止运行并开始递减计数,这会影响我的数据库,因此mysql无法继续回显剩余时间。我该怎么办?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Timer</title>
</head>
<script type="text/javascript" href="//code.jquery.com/jquery-3.3.1.min.js
"></script>
<body>
<form method="post">
<div>
<div class="row justify-content-center" style="
text-align: center;margin-bottom: 20px; z-index: 1;">
<input type="number" id="time_hr" value="00" style="width: 40px; text-align: center;" maxlength="2">
:<input type="number" id="time_min" value="00" style="width: 40px; text-align: center;" maxlength="2">
:<input type="number" id="time_sec" value="00" style="width: 40px; text-align: center;" maxlength="2">
<input type="button" id="btn_Time" value="GO" onclick="startNa()">
</div>
<div>
</div><br>
<div class="row" style="z-index: 1;">
<p id="time1" style="font-size: 50px; text-align: center;"></p>
</div>
</div>
<script>
$(document).ready(function(){
setInterval(getTimer1, 1000);
});
var ctr;
var timerInterval;
function timerKo() {
var minShow = parseInt(ctr/60) < 10 ? "0"+ parseInt(ctr/60) : parseInt(ctr/60);
var hourShow = parseInt(ctr/3600) < 10 ? "0"+parseInt(ctr/3600) : parseInt(ctr/3600);
var secShow = ctr%60 < 10 ? "0"+(ctr%60) : (ctr%60);
// document.getElementById('time1').innerHTML = hourShow+":"+ minShow+":"+secShow;
// document.getElementById("counter1").innerHTML = ctr;
$.post('updateTimerTime.php',
{
'timer1_update':true,
'seconds': ctr
},function(data, status)
{
// alert(data);
});
ctr--;
if(ctr == -1) {
// <?php
// shell_exec - off
// ?>```````
alert("ZERO Na");
clearInterval(timerInterval);
}
}
function startNa() {
var sec = parseInt(document.getElementById("time_sec").value);
var min = parseInt(document.getElementById("time_min").value);
var hour = parseInt(document.getElementById("time_hr").value);
hour = hour * 60 * 60;
min = min * 60;
sec = sec;
ctr = hour + min + sec;
timerInterval = window.setInterval(timerKo, 1000);
}
function getTimer1()
{
$.post('getTimerTime.php',
{
'getTimer1': true
}, function(data, status){
$("#time1").html(data);
});
}
</script>
</form>
</body>
</html>
<?php
require 'conn.php';
if(isset($_POST['timer1_update']))
{
// echo "TIIMER ";
$seconds = $_POST['seconds'];
$sql = "UPDATE timers SET timerswitch='$seconds' WHERE id=1";
mysqli_query($db, $sql);
}
?>
<?php
require 'conn.php';
if (isset($_POST['getTimer1'])) {
$sql = "SELECT * FROM timers WHERE id=1";
$result = mysqli_query($db, $sql);
$data = mysqli_fetch_array($result);
$time_1 = $data['timerswitch'];
$sec_1 = intval($time_1%60) < 10 ? 0 . intval($time_1%60) : intval($time_1%60);
$min_1 = intval(($time_1/60)%60) < 10 ? 0 . intval(($time_1/60)%60) : (($time_1/60)%60);
$hr_1 = intval($time_1/3600) < 10 ? 0 . intval($time_1/3600) : intval($time_1/3600);
echo $hr_1 . ":" . $min_1 . ":" . $sec_1;
}
?>