有谁知道以下场景最适合使用什么函数?
当歌曲开始播放时,我想启动一个以秒为单位的“秒表”。
在任何时候,我都希望能够调用此变量,例如您单击的按钮将执行警报(时间)
并显示计时器的计数。
但是,当我运行函数reset-timer();
时,我希望这一切都能重置并重新开始计数。
我在考虑 settimeout 或 setinterval 但不确定哪个是正确的。
谢谢:)
最佳答案
以下是帮助您入门的基本概念: http://jsfiddle.net/V29qK/1/
var startTime = new Date();
function SetTime(){
var curTime = new Date();
var seconds = Math.round((curTime - startTime) / 1000) + " second(s)";
document.getElementById("timer").innerHTML = seconds;
}
var interval = setInterval(SetTime, 1000);
function ResetTime(){
document.getElementById("timer").innerHTML = "0 second(s)";
startTime = new Date();
}
逻辑是:将全局变量设置为 new Date()
以表示开始时间。在某个时间间隔(或超时)内,获取当前的 new Date() 并从中减去开始时间。这将为您提供以毫秒为单位的差异。然后,您可以使用此数据更新您想要的任何 UI 元素。
要“重置”计时器,只需使用 new Date()
将开始时间设置为当前时间
关于javascript - Jquery 设置计数器,但在调用函数时重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12356316/