Javascript 如何创建计时器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13763879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a timer
提问by user1881090
I have a $dbSessionDurationvariable where by using mysqli, it is able to bind the result of data from the query into this variable. The $dbSessionDurationvariable holds time so the variable has a time format as below:
我有一个$dbSessionDuration变量,通过使用 mysqli,它能够将查询中的数据结果绑定到这个变量中。该$dbSessionDuration变量保存时间,因此该变量的时间格式如下:
01:30:10
01:30:10
Now that means 1 hour 30 mins and 10 seconds. What I want to do is display $dbSessionDurationvalue in a timer so that in above's example it will start ticking down from 01:30:10 and go all the way to 0 when it stops. My question is how do you create timer and place whatever value $dbSessionDurationvalue in the timer to count down to 00:00:00?
现在这意味着 1 小时 30 分 10 秒。我想要做的是$dbSessionDuration在计时器中显示值,以便在上面的示例中,它将从 01:30:10 开始滴答滴答,并在停止时一直到 0。我的问题是如何创建计时器并$dbSessionDuration在计时器中放置任何值以倒计时到 00:00:00?
回答by alexmngn
First of all, you have to convert your time in seconds.
首先,您必须以秒为单位转换时间。
<?php
list($hour,$min,$sec) = explode(':', $dbSessionDuration);
$dbSessionDurationTime = mktime(0,0,0,$hour,$min,$sec);
?>
To create a countdown, you have to use Javascript.
要创建倒计时,您必须使用 Javascript。
<script type="text/javascript">
var millis = <?php echo $dbSessionDurationTime; ?>
function displaytimer(){
var hours = Math.floor(millis / 36e5),
mins = Math.floor((millis % 36e5) / 6e4),
secs = Math.floor((millis % 6e4) / 1000);
//Here, the DOM that the timer will appear using jQuery
$('.count').html(hours+':'+mins+':'+secs);
}
setInterval(function(){
millis -= 1000;
displaytimer();
}, 1000);
</script>
I didn't test, but that should work!
我没有测试,但这应该有效!
回答by Khez
You should first know, that anyJavaScript timer you create will be inaccurate. This is due to a myriad of reasons summed up very nicely here.
您首先应该知道,您创建的任何JavaScript 计时器都是不准确的。这是由于无数的原因在这里总结得非常好。
Now the beauty is, you can make limit the inaccuracy of your scripts by a simple check of the system time of the user on each iteration. Yes the system time of the user.
现在的好处是,您可以通过在每次迭代时简单检查用户的系统时间来限制脚本的不准确性。是用户的系统时间。
In your situation this is not a problem, because you're interested in elapsed time (01:30:10), but if you were waiting for a specific moment in time, you would need to handle time-zone differences or just a badly set clock on a user's computer.
在您的情况下,这不是问题,因为您对经过的时间 (01:30:10) 感兴趣,但是如果您正在等待特定的时间,则需要处理时区差异或只是在用户的计算机上设置时钟。
What you also have to understand, is that if this is a problem of security, you will not be able to account for changes to the system clock post loading your script.
您还必须了解的是,如果这是一个安全问题,您将无法考虑加载脚本后系统时钟的更改。
Example:Some sites force you to wait before doing a specific action. But changing your clock ahead, would in most cases help you bypass poor security. In most cases, it wouldn't because secondary checks are done server side. What I'm trying to say, is make those server side checks.
示例:某些站点强制您在执行特定操作之前等待。但是,提前更改时钟在大多数情况下可以帮助您绕过安全性差的问题。在大多数情况下,它不会,因为二次检查是在服务器端完成的。我想说的是让那些服务器端检查。
To answer your question, I would personally calculate the number of seconds that are required to pass:
为了回答你的问题,我会亲自计算需要通过的秒数:
$time = explode(':',$dbSessionDuration);# get hour, minutes, seconds to be elapsed
$time = $time[2] + $time[1] * 60 + $time[0] * 3600;# get elapse time in seconds
In your JavaScript file you could do something like this:
在您的 JavaScript 文件中,您可以执行以下操作:
(function(endTime){
endTime*=1000; // javascript works with milliseconds
endTime+=new Date().getTime();// add the current system time into the equation
// your timeSync function
(function timerSync() {
var diff = new Date(endTime - new Date().getTime());
var timer=document.getElementById('timer');
if(diff<=0)return timerEnd(timer);
timer.innerHTML =
doubleDigits(diff.getUTCHours())
+ ':' +
doubleDigits(diff.getUTCMinutes())
+ ':' +
doubleDigits(diff.getUTCSeconds())
;
setTimeout(timerSync,1000);
})();// also call it to start the timer
// your timer end function
function timerEnd(timer) {
timer.innerHTML='Timer has stopped now';
}
// double digit formatting
function doubleDigits(number) {
return number<10
? '0'+number
: number
;
}
})(
<?php echo $time;?>
);// time to elapse 1:30:10
Here is a working fiddle, but do remember. This is not optimized for your specific case. You could still wrap it up in an object, if you have two timers on the page, don't double up closure memory with functions that act absolutely the same.
这是一个工作小提琴,但请记住。这并未针对您的特定情况进行优化。您仍然可以将其包装在一个对象中,如果页面上有两个计时器,请不要使用完全相同的函数将闭包内存加倍。
If you have any questions, ask in a comment and I'll try to help.
如果您有任何问题,请在评论中提问,我会尽力提供帮助。
回答by sv_in
Code: http://jsfiddle.net/g3rRJ/
代码:http: //jsfiddle.net/g3rRJ/
I split the time into hours, minutes and seconds. and every second decremented the clock. Algo is pretty straight forward I believe:
我把时间分成小时、分钟和秒。并且每一秒都在减少时钟。我相信 Algo 非常简单:
var timer = setInterval(function(){
seconds--;
if(seconds == -1) {
seconds = 59;
minutes--;
if(minutes == -1) {
minutes = 59;
hours--;
if(hours==-1) {
alert("timer finished");
clearInterval(timer);
return;
}
}
}
span.text(correctNum(hours) + ":" + correctNum(minutes) + ":" + correctNum(seconds));
}, 1000);
回答by Terafor
Use jQuery as you own it.
使用 jQuery,就像你拥有它一样。
Here is a nice plugin https://github.com/jylauril/jquery-runner
这是一个不错的插件https://github.com/jylauril/jquery-runner
and this is an example of it:
这是一个例子:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.0.min.js"></script>
<script src="https://raw.github.com/jylauril/jquery-runner/master/build/jquery.runner-min.js"></script>
</head>
<body>
<span id="runner"></span>
<script type="text/javascript">
$(document).ready(function(){
$('#runner').runner({
autostart: true,
countdown: true,
stopAt: 0,
startAt: 30000 // alternatively you could just write: 30*1000
});
});
</script>
</body>
</html>
回答by Martin
if you need a timer you can use this plugin in Jqueryit works great. You'd just put The time or $dbSessionDuration in a hidden element of HTML after reading it and put it to jquery counter plugin. If the idea sounds interesting let me know and I leave an example.
如果你需要一个计时器,你可以在 Jquery 中使用这个插件,它工作得很好。您只需在阅读后将时间或 $dbSessionDuration 放入 HTML 的隐藏元素中,然后将其放入 jquery 计数器插件。如果这个想法听起来很有趣,请告诉我,我会留下一个例子。
回答by A.A Noman
You can do this more easy way. First You have to retrieve time from database which is already in seconds
你可以用更简单的方法做到这一点。首先,您必须从已经以秒为单位的数据库中检索时间
<?php
require_once 'db_connect.php';
$sql = "SELECT * FROM ac_one_config";
$result = $con->query($sql);
if( $result->num_rows > 0 ){
while($row=mysqli_fetch_assoc($result)) {
$time_on = $row['ac_on_time'];
}
}
header( "refresh:$time_on; url=https://localhost/your_project/file.php");
In Javascript the countdown start and countdown start from time $time_onuntil 0:00:00
在 Javascript 中,倒计时开始和倒计时从时间开始,$time_on直到 0:00:00
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Massive Electronics</title>
<style type="text/css">
.myClass {
font-family: verdana;
font-size: 16px;
font-weight: normal;
color: black;
line-height: 30px;
}
</style>
</head>
<body>
<script type="text/javascript">
(function () {
var timeLeft = <?php echo $time_on; ?>,
cinterval;
var timeDec = function (){
timeLeft--;
document.getElementById('countdown').innerHTML = timeLeft;
if(timeLeft === 0){
clearInterval(cinterval);
}
};
cinterval = setInterval(timeDec, 1000);
})();
</script>
Redirecting in <span id="countdown"><?php echo floor($time_on); ?></span> seconds.<br><br>
<span class="myClass">Ac ON Page</span>
</body>
</html>
回答by Pkalra
Set the time duration and store this value in session variable.
设置持续时间并将此值存储在会话变量中。
<div id="timer"></div>
<?php
$_SESSION['TIME_DURATION'] = 45;
$_SESSION['start_time'] = date("Y-m-d H:i:s");
$end_time = date("Y-m-d H:i:s", strtotime('+'.$_SESSION['TIME_DURATION'].'minutes',strtotime($_SESSION['start_time'])));
if(!isset($_SESSION['end_time']) && empty($_SESSION['end_time'])){
$_SESSION['end_time'] = $end_time;
}
?>
var myVar = setInterval(myTimer, 1000);
function myTimer() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","response.php",false);
xmlhttp.send(null);
if(xmlhttp.responseText == "Time Out"){
myStopFunction();
}
$('#timer').html(xmlhttp.responseText);
}
function myStopFunction() {
clearInterval(myVar);
}
File: response.php
session_start(); if(isset($_SESSION['TIME_DURATION']) && $_SESSION['TIME_DURATION'] != 0 ){ $time_first = strtotime(date("Y-m-d H:i:s")); $time_second = strtotime($_SESSION['end_time']); $differenceinseconds = $time_second - $time_first; $time_lapse=gmdate("i:s",$differenceinseconds); if($time_lapse=='00:00') { echo "Time Out"; unset($_SESSION['start_time']); unset($_SESSION['end_time']); unset($_SESSION['TIME_DURATION']); }else { echo gmdate("i:s",$differenceinseconds); } }else{ echo "Time Out"; }
文件:response.php
session_start(); if(isset($_SESSION['TIME_DURATION']) && $_SESSION['TIME_DURATION'] != 0 ){ $time_first = strtotime(date("Y-m-d H:i:s")); $time_second = strtotime($_SESSION['end_time']); $differenceinseconds = $time_second - $time_first; $time_lapse=gmdate("i:s",$differenceinseconds); if($time_lapse=='00:00') { echo "Time Out"; unset($_SESSION['start_time']); unset($_SESSION['end_time']); unset($_SESSION['TIME_DURATION']); }else { echo gmdate("i:s",$differenceinseconds); } }else{ echo "Time Out"; }

