如何保存计时器中的时间,然后再继续?
Posted
技术标签:
【中文标题】如何保存计时器中的时间,然后再继续?【英文标题】:how can I save the time in the timer, and resume later? 【发布时间】:2022-01-21 16:59:41 【问题描述】:所以我有一个计时器和一个使用 JSON 的保存文件。 这就是 json 文件的样子,例如:
"name": "shinx",
"imageurl": "https://poketch-cdn-assets.s3.amazonaws.com/images/pokemon/animated/shiny/shinx.gif",
"method": "pokeradar",
"counter": 0,
"shinycharm": false,
"masuda": false
这是定时器代码:
// Convert time to a format of hours, minutes, seconds, and milliseconds
function timeToString(time)
let diffInHrs = time / 3600000;
let hh = Math.floor(diffInHrs);
let diffInMin = (diffInHrs - hh) * 60;
let mm = Math.floor(diffInMin);
let diffInSec = (diffInMin - mm) * 60;
let ss = Math.floor(diffInSec);
let diffInMs = (diffInSec - ss) * 100;
let ms = Math.floor(diffInMs);
let formattedHH = hh.toString().padStart(2, "0");
let formattedMM = mm.toString().padStart(2, "0");
let formattedSS = ss.toString().padStart(2, "0");
let formattedMS = ms.toString().padStart(2, "0");
return `$formattedHH:$formattedMM:$formattedSS`;
// Declare variables to use in our functions below
let startTime;
let elapsedTime = 0;
let timerInterval;
// Create function to modify innerhtml
function print(txt)
document.getElementById("Timer").innerHTML = txt;
// Create "start", "pause" and "reset" functions
function start()
startTime = Date.now() - elapsedTime;
timerInterval = setInterval(function printTime()
elapsedTime = Date.now() - startTime;
print(timeToString(elapsedTime));
, 10)
function pause()
clearInterval(timerInterval);
// Create event listeners
let playButton = document.getElementById("playButton");
let pauseButton = document.getElementById("pauseButton");
playButton.addEventListener("click", start);
pauseButton.addEventListener("click", pause);
我保存json文件的方法是这样的:
document.getElementById("saveButton").addEventListener('click',()=>
//Save the counter here (there is a code above that counts click ignore this one, not related to the question)
finalcurrenthunt.counter=counter;
//save the timer here
//timer save code (what variables do I need to save inside the json file in order to continue from where I paused the timer)
//save the json to a selected folder
const huntsaved = JSON.stringify(finalcurrenthunt,null,2);
const finalhuntsaved = huntsaved.replaceAll('\n',"")
alert("Please Click On The Save File, When Asked To Replace Please Do So.")
ipcRenderer.send("create-document-trigger",finalhuntsaved);
)
我想在暂停后保存计时器,当我退出应用程序并重新启动时,加载保存文件,我将从上次保存的值开始。
示例: 我使用计时器直到我到达 00:0025, 我在 00:00:25 的计时器时保存了文件, 我想再次使用计时器,所以我打开应用程序并加载保存文件以从 00:00:25 继续,而不是完全重新启动计时器
我怎样才能做到这一点?
【问题讨论】:
这能回答你的问题吗? How do I store my countdown timer in a cookie so that it will continue counting down even when leaving or reloading the page? 【参考方案1】:我的问题很简单,我不得不以一种奇怪的方式来节省经过的时间?
我将 let ElapsedTime 推到我的文件顶部(因为您在此处看到的所有内容都在我的 js 的底部) 我在清除间隔之前设置了暂停功能
saveTimer = ElapsedTime;
然后转到我的保存方法并添加
finalcurrenthunt.timer=saveTimer;
【讨论】:
以上是关于如何保存计时器中的时间,然后再继续?的主要内容,如果未能解决你的问题,请参考以下文章