有没有办法这样做?我想创建一个可以从最后一个检查点"恢复"应用程序的 JavaScript 应用程序,例如
//code.js
var abc = 13;
checkpoint("myLocalStorage");
alert(abc);
检查点函数将存储有关执行的所有信息,以便将来可以在离开的位置恢复执行:
//resume.js
resume("myLocalStorage");
这对于执行具有巨大循环的长脚本/脚本非常有帮助 - 我不是在谈论执行一些预加载图像或执行一些有趣动画的小脚本。我说的是使用 JavaScript 作为真正的数字处理工具,其中执行可能需要很长时间并且需要巨大的计算能力。在这些上下文中,您可以看到执行检查点是多么有用!
我想这样的东西在 JavaScript 中还不存在,但如果有人接近与它非常相似的东西,我仍然会非常感激。
为了在Javascript中制作"可挂起"的东西,你需要用与普通程序略有不同的方式来表述。
步骤 1
决定你能一次性完成多少问题,因为缺乏更好的词。
步骤 2
将状态存储在某种对象中。 您没有中间值,只有进行下一次传递所需的确切值
步骤 3
编写代码,使其可以使用window.setTimeout()
函数运行。 这使得测试比重新加载页面容易得多。
在这种情况下,我有一个程序可以将我的全名转换为小写,一次一步。 我唯一需要保存的数据是我的名字,以及我在计算过程中的位置的索引。
示例 1:使用setTimeout()
<html>
<head>
<title>Test Thingy</title>
</head>
<body>
<script>
var data = {
name: ["Jeremy", "J", "Starcher"],
idx: 0
}
function doPass() {
// If at the end of the list
if (data.idx >= data.name.length) {
alert("All iterations done:" + data.name.join(" "));
return;
}
// Do our calculation here
var s = data.name[data.idx];
s = s.toLowerCase();
data.name[data.idx] = s;
data.idx++;
window.setTimeout(doPass);
}
doPass();
</script>
</body>
</html>
示例 2:使用本地存储。 点击"重新加载"4次进行测试
<html>
<head>
<title>Test Thingy</title>
</head>
<body>
<script>
var data;
data = localStorage.getItem("data");
if (data) {
data = JSON.parse(data);
} else {
data = {
name: ["Jeremy", "J", "Starcher"],
idx: 0
}
}
function doPass() {
// If at the end of the list
if (data.idx >= data.name.length) {
alert("All iterations done:" + data.name.join(" "));
return;
}
// Do our calculation here
var s = data.name[data.idx];
alert(s);
s = s.toLowerCase();
data.name[data.idx] = s;
data.idx++;
localStorage.setItem("data", JSON.stringify(data));
}
doPass();
</script>
</body>
</html>
Javascript不是为"[存储]实数处理工具而设计的,其中执行可能需要很长时间并且需要巨大的计算能力"。以下是您将获得的最好的: http://www.w3schools.com/html/html5_webstorage.asp
最新的浏览器支持 yield
.我们可以研究一下。
https://developer.mozilla.org/en-US/docs/JavaScript/New_in_JavaScript/1.7