javascript - javascript 计时器和 sessionStorage
问题描述
我有以下问题。我有一个计时器功能,它需要一个参数,即秒数。直接通过时,它可以正常工作。但是,出于多种原因,我需要使用 sessionStorage,当我在将变量传递给计时器函数之前从 sessionStorage 中检索变量时,它将参数中传递的秒数乘以 10。我不明白为什么它有这种行为。我写了一个最小的例子来说明我的问题:
function countdown(time_p) {
var saved_countdown = sessionStorage.getItem('saved_countdown');
var time;
if (saved_countdown == null) {
// Set the time we're counting down to using the time allowed
var new_countdown = new Date().getTime() + (time_p + 2) * 1000;
time = new_countdown;
sessionStorage.setItem('saved_countdown', new_countdown);
} else {
time = saved_countdown;
}
// Update the count down every 1 second
var x = setInterval(() => {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the allowed time
var distance = time - now;
// Time counter
var counter = Math.floor(distance / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = counter + " s";
// If the count down is over, write some text
if (counter <= 0) {
clearInterval(x);
sessionStorage.removeItem('saved_countdown');
sessionStorage.removeItem('max_time');
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
}
$("#confirm_settings").click(function() {
var time = $("#time").val();
console.log("time entered" + time);
sessionStorage.setItem('max_time', time);
time = sessionStorage.getItem('max_time'); // multiply the time entered by 10 ...
// time = 42; // works well
console.log("time = " + time);
countdown(time);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<p id="demo"> </p>
<label for "time"> Time limit :</label>
<input type="text" id="time" placeholder="enter a duration (s)"> <br>
<button type="button" id="confirm_settings">OK</button>
解决方案
窗口存储保存字符串。您需要将它们转换为整数:
function countdown(time_p) {
var time = sessionStorage.getItem('saved_countdown');
if (time) {
time = +time; // cast the string to number
}
else {
// Set the time we're counting down to using the time allowed
var new_countdown = new Date().getTime() + (time_p + 2) * 1000;
time = new_countdown;
sessionStorage.setItem('saved_countdown', new_countdown);
}
推荐阅读
- jsp - 如何在一个 JSP 页面上执行 mySQL 查询并在另一个页面上显示结果?
- mysql - 将 mysql 数据转储导入 Maria DB
- javascript - 如何在我的 React Todo 列表中实现 React Beautiful 拖放功能?
- python - 如何在python中加密套接字连接
- create-react-app - 为什么我只在 CRA 构建期间收到 ESLint 警告,而在 CLI 上运行 Eslint 时却没有?
- django - 我不明白如何使用 django 3rd 方库 djangorestframework-api-key
- image - 如何在 OpenShift 上列出所有 docker 图像信息
- apache-flink - Flink 读取 Savepoint 的 keystate 时,任务一直在运行,无法完成
- java - 项目 Reactor 中的并行通量与通量
- javascript - 当我映射一个 fetch 调用时,我怎么知道要写什么