全局变量 i 没变化,一直是0,为什么loop()里面改变的i,没有反映到外面的i呢?可是chrome 里调试,手动运行loop();后,再输入i,它会变化的,由1变到10.
function loop ()
{
if (i < 10 )
{
setTimeout(
function () { i++; loop(); },1000);
}
else
return true;
}
var i = 0;
loop();
while (true)
{
if (i > 0 );
alert (i);
}
function loop ()
{
if (i < 10 )
{
setTimeout(
function () { i++; loop(); },1000);
}
else
return true;
}
var i = 0;
loop();
while (true)
{
if (i > 0 );
alert (i);
}
如果在定时器的间隔内再有其它事件如alert让脚本暂停,则定时器也会暂停的。定时器并不会在后台运行。比如你的例子,当前脚本的alert让定时器根本就没有启动。
我改了一下,把当前的alert注释掉,在loop里增加一个显示语句,你可以看到定时器里的变量i
是在增加的。同时,我增加了一个按钮,在定时器执行到中间某处,比如i=6时,按下按钮,alert来让js暂停一会,按确认后可以看到,定时器是从暂停的地方继续执行的。并没有在后台走。 <input type="button" value="alert" onclick="alert('hi')" />
<div id="div1">div1</div>
<script type="text/javascript">
function loop() {
document.getElementById("div1").innerHTML = i;
if (i < 10) {
setTimeout(function() { i++; loop(); }, 1000); }
else return true;
}
var i = 0;
loop();
</script>
function test()
{
for(i = 0; i < 3; i++)
{
loop(i);
}
return true;
}由于loop的执行的时间是不确定的,根据它的参数,有时长,有时短.
所以,上面test的返回结果也是不正确的,由于loop有延时,没等它做完,test已经返回结果了.
我是想,loop由0-2做完后,再返回结果的.
但是,想不出怎么搞.
<script type="text/javascript">
var i=0,test=document.getElementById("test"),timer;
timer=window.setInterval(function(){
i+=1;
if(i>=10){
window.clearInterval(timer);
test.innerHTML+=("10次了<br />");
}else{
test.innerHTML+=(i+"<br />");
}
},500)
</script>
{
if (i < 10 )
{
setTimeout(
function () { i++;alert(i); loop(); },1000);
}
else
return true;
}
var i = 0;
loop();
先后执行不同的逻辑的定时器的话,
就是在每一个定时器结束的时候,启动下一个定时器就行了
我这里给你一个例子,移动小球先向左,再向下,再左上,然后结束。<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>自动移动小球</title>
<style type="text/css" >
#box{ position:relative; width:800px;height:600px; border:1px solid red;}
#ball{ position:absolute;border:1px solid blue;height:10px;width:10px; }
</style>
</head>
<body >
<input type="button" value="移动小球" onclick="startmove()" />
<div id="box">
<div id="ball"></div>
</div>
<script type="text/javascript" >
var x = 0, y = 0;
var oball = document.getElementById("ball");
var timer;
function startmove() {
timer = window.setInterval("moveleft()", 20);
} function moveleft() {
x++;
if (x < 100) {
oball.style.left = x+"px" ; }
else {
window.clearInterval(timer)
timer = window.setInterval("movedown()", 20);
}
} function movedown() {
y++;
if (y < 100) { oball.style.top = y + "px" } else {
window.clearInterval(timer)
timer = window.setInterval("movelefttop()", 20);
}
} function movelefttop() {
x--;y--;
if (x > 0 && y > 0) {
oball.style.left = x + "px";
oball.style.top = y + "px";
}
else{window.clearInterval(timer);alert("所有定时器结束")}
}
</script>
</body>
</html>