如何节省秒表的时间并在另一个HTML页面中显示该时间

时间:2019-06-16 20:45:28

标签: javascript html local-storage

function runTimer() {
    currentTime = leadingZero(timer[0]) + ":" + leadingZero(timer[1]) + ":" + leadingZero(timer[2]);

    theTimer.innerHTML = currentTime;
    timer[3]++;

    timer[0] = Math.floor((timer[3]/100)/60);
    timer[1] = Math.floor((timer[3]/100) - (timer[0] * 60));
    timer[2] = Math.floor(timer[3] - (timer[1] * 100) - (timer[0] * 6000));
}

因此,我目前正在使用javascript进行打字测试项目,而我的程序当前的工作方式是,当用户首次开始键入提示时,秒表计时器将开始为用户计时。用户完成提示输入后,秒表将停止计时,然后将用户带到应显示用户时间的结束页面。但是我在尝试节省用户时间方面遇到了问题。例如,如果用户A在15秒内完成测试,则程序应保存用户的时间,然后在下一页显示该信息,我将带他们去。

我尝试使用localStorage.setItem函数,但最终在页面上得到[object HTML Element]而不是得分。下面,我附上了与程序的计时器功能有关的代码。我基本上想通过使用本地存储来节省时间,但是它不起作用。

2 个答案:

答案 0 :(得分:0)

我想到的最简单的解决方案是在新URL中将用户的时间作为参数发送。计时停止后,添加以下行:

window.location = 'your/new/page/location.html?time=' + time;

time-是用户的时间。如您所见,参数在“?”之后标志。因此,在新页面上,您将可以在此行中获取此参数:

var usersTime = window.location.search.split('=')[1];

“搜索”方法将URL的部分放在“?”之后。符号(包括它)-将是“?time = 15”。然后用'='分隔这行作为分隔符,并取第二部分,即数字15。

答案 1 :(得分:0)

本地存储将项目存储为字符串。 因此,最简单的方法是存储开始时间和结束时间。

因此,当用户启动时,请致电:

window.localStorage.setItem("starttime", Date.now());

当用户完成操作后,致电:

window.localStorage.setItem("endtime", Date.now());

这将为您提供2个时间戳,您可以将其用于格式化显示。

使用以下方法在下一页获取时间戳:

starttime = window.localStorage.getItem("starttime");
endtime = window.localStorage.getItem("endtime");

totalseconds = (endtime - starttime) / 1000;

然后使用totalseconds来计算小时/分钟/秒等

如果您需要在用户键入时在屏幕上显示计时器,则可以使用

totalseconds = (Date.now() - window.localStorage.getItem("starttime")) / 1000;

我已经在Chrome中对此进行了测试,并且效果很好。