0
我试图在屏幕上逐渐显示文本(如字幕)。例如H ..他..地狱..你好。当我在VS2010中进行调试时,它正在工作!但是当它实际运行时,它会立即显示整个句子。函数调用函数WEIRD结果
我在每个字母之间做了一定的“延迟”约3秒,所以它会假设需要一段时间,但实际上它会立即显示一切。
谁是解决这个谜的天才? (请不要给我建议如何创建marquee效果,这不再是问题,现在它只是我和javascript之间的WAR!)我假设它在从函数调用函数时与同步有关?
感谢任何人会帮助我恢复理智。
您可以下载代码从这里(VS项目): http://pcgroup.co.il/downloads/misc/function_from_function.zip
或查看在这里:
<body>
<script type="text/javascript">
//trying to display this source sentence letter by letter:
var source = "hi javascript why are you being such a pain";
var target = "";
var pos = 0;
var mayGoOn = false;
//this function calls another function which suppose to "build" the sentence increasing index using the global var pos (it's even working when following it in debug)
function textticker() {
if (pos < source.length) {
flash();
if (mayGoOn == true) {
pos++;
mayGoOn = false;
document.write(target);
textticker();
}
}
}
function flash() {
//I tried to put returns everywhere assuming that this may solve it probably one of them in not necessary but it doesn't solve it
if (mayGoOn == true) { return; }
while (true) {
var d = new Date();
if (d.getSeconds() % 3 == 0) {
//alert('this suppose to happen only in about every 3 seconds');
target = source.substring(0, pos);
mayGoOn = true;
return;
}
}
}
textticker();
</script>
你应该看看'setTimeout'或'setInterval'功能。 – 2012-01-11 10:35:12
这不是你在同步上下文中做延迟的方式。查找'setTimeout'。 – 2012-01-11 10:35:17
除了塞尔吉奥的回答,这不起作用的原因是循环每秒发生一次以上,所以d.getSeconds()%3 == 0将每3秒成千上万次。它在调试中起作用的原因是你大量减慢了执行速度。为了让它工作,你必须检查你和上次不一样。这也将是UI阻塞,所以不是一个好主意。 – mattmanser 2012-01-11 10:42:47