为了在 Javascript 中创建“可挂起”的东西,你需要用不同于普通程序的方式来制定一些东西。
第 1 步
决定你能在一次pass中解决多少问题,因为没有更好的词。
第 2 步
将状态存储在某种对象中。您没有中间值,只是进行下一次 pass
所需的值
第 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:使用 localStorage。点击“重新加载”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>