为了使一些在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:使用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>
出于好奇,你知道的*有这样的功能,任何*语言? –
@GGG:C具有的setjmp()和longjmp()。另请参阅C#5异步或协程。 – SLaks
@SLaks由于某种原因,我认为程序状态应该被保存,这应该在跨会话中工作......也许我读错了问题。 –