利用jQuery+localStorage实现一个简易的计时器示例代码

2020-05-27 18:00:27易采站长站整理

//按下暂停/恢复的时钟秒表
/*stopwatchClock.on('click',function(){
if(stopwatchClock.hasClass('inactive')){
startStopwatch()
}
else{
pauseStopwatch();
}
});*/
/*开始计时*/
function startStopwatch(){
// 防止多个间隔同时进行。
clearInterval(stopwatchInterval);
var startTimestamp = new Date().getTime(),
runningTime = 0;
localStorage.stopwatchBeginingTimestamp = startTimestamp;
// 应用程序还记得上一次会话运行了多长时间。
if(Number(localStorage.stopwatchRunningTime)){
runningTime = Number(localStorage.stopwatchRunningTime);
}
else{
localStorage.stopwatchRunningTime = 1;
}
// 每隔100ms重新计算运行时间,计算公式是
// 当你上次启动时钟+上次运行时间
stopwatchInterval = setInterval(function () {
var stopwatchTime = (new Date().getTime() - startTimestamp + runningTime);
stopwatchDigits.text(returnFormattedToMilliseconds(stopwatchTime));
}, 100);
stopwatchClock.removeClass('inactive');
}
/*停止计时*/
function pauseStopwatch(){
// 停止计时
clearInterval(stopwatchInterval);
if(Number(localStorage.stopwatchBeginingTimestamp)){
// 计算运行时间。
// 新的运行时间=上次运行时间+现在-最后一次启动
var runningTime = Number(localStorage.stopwatchRunningTime) + new Date().getTime() - Number(localStorage.stopwatchBeginingTimestamp);
localStorage.stopwatchBeginingTimestamp = 0;
localStorage.stopwatchRunningTime = runningTime;
stopwatchClock.addClass('inactive');
}
}
// 重置.
/*function resetStopwatch(){
clearInterval(stopwatchInterval);
stopwatchDigits.text(returnFormattedToMilliseconds(0));
localStorage.stopwatchBeginingTimestamp = 0;
localStorage.stopwatchRunningTime = 0;

stopwatchClock.addClass('inactive');
}
*/
function returnFormattedToMilliseconds(time){
var
seconds = Math.floor((time/1000) % 60),
minutes = Math.floor((time/(1000*60)) % 60),
hours = Math.floor((time/(1000*60*60)) % 24);
seconds = seconds < 10 ? '0' + seconds : seconds;
minutes = minutes < 10 ? '0' + minutes : minutes;
return hours + ":" + minutes + ":" + seconds;
}
</script>

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对软件开发网的支持。