JavaScript中的setTimeout()与setInterval()都是指延时执行某一操作。
但setInterval()指每隔指定时间执行某操作,会循环不断地执行该操作;setTimeout()只延时指定时间后执行该操作,且只执行一次。
setTimeout()在某种情况下也能实现setInterval()的效果,比较经典的例子就是在在函数内部调用自己。向下面这样:
function example(){
...
setTimeout("example()", 1000);
}
下面给一个走马灯的例子:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>走马灯</title> <script> var i = -100; function setColor() { var color = new Array("red","blue","green","black","turquoise","coral","orange","lime","violet"); var i = Math.round(Math.random()*8); document.getElementById("text").style.color = color[i]; } function setScroll() { var text = document.getElementById("text"); text.style.marginLeft = i + "px"; i = i + 10; if(i > 200){i = -100;} setTimeout("setScroll()",500); } function changeColor() { setInterval("setColor()",500); } function func() { changeColor(); setScroll(); } </script> </head> <body onLoad="func()"> <div style="width:200px; overflow:hidden; background-color:#CCC;"><div id="text" style="width:100px;">显示随机颜色</div></div> </body> </html>
时间: 2024-12-27 20:59:45