我正在做一些‘网络进化模型’的可视化类似的事情。
基本算法是:
因此,基本上,我必须重复这100个进化步骤3次,在两者之间进行独特的操作,然后再从头开始。
我的当前代码的结构有点像这样:
var timer;
var counter;
function bigFunction() {
function hundredSteps() {
// code for single step
timer = setTimeout(hundredSteps(), 10);
counter++;
stage++;
if (counter >= 100) {
clearTimeout(timer);
counter = 0;
nextStage(stage);
}
}
function nextStage(stage) {
if (stage == 1) {
// 1st step code, some init operations
timer = setTimeout(hundredSteps(), 10);
}
if (stage == 2) {
// 2nd step code, some operations
timer = setTimeout(hundredSteps(), 10);
}
if (stage == 3) {
// 3rd step code, some other operations
stage = 0;
timer = setTimeout(hundredSteps(), 10);
}
}
var stage = 1;
counter = 0;
nextStage(stage);
} 所以我想问:这是一种编码我想要实现的目标的“适当”方式吗?或者,人们通常会有不同的做法吗?
发布于 2014-04-25 12:42:10
要使用set,您需要将函数放入其中,而不是调用它。就像这样:
setTimeout(hundredSteps, 10)或
setTimeout(function() {
hundredSteps()
}, 10)举个例子,我会把这一切都清理一下。在您的问题中,当计数器在下一步函数中增加时,您的阶段就会增加。您也有一个变量来跟踪计时器,当它不是完全必要的时候。
下面是一个工作示例的小提琴:http://jsfiddle.net/Czr8T/1/
var counter = 0,
stage = 1
var hundredSteps = function() {
counter++
//Your code here
if (counter >= 100) {
counter = 0
nextStage()
} else {
window.setTimeout(hundredSteps, 10)
}
}
var nextStage = function() {
switch (stage) {
case 1:
//Your code here
console.log("Stage one activated")
break
case 2:
//Your code here
console.log("Stage two activated")
break
case 3:
//Your code here
stage = 0
console.log("Stage three activated")
break
}
stage++
window.setTimeout(hundredSteps, 10)
}
nextStage()https://stackoverflow.com/questions/23293345
复制相似问题