Javascript之计时器
知识归纳:
setInterval(代码,交互时间); //代码是指要调用的函数或者代码串,每隔指定交互时间执行代码,交互时 间以毫秒记,特点是会循环反复执行。
clearInterval(代码,交互时间); //取消setInterval的设置
setTimeout(代码,交互时间); // 指定的交互时间来执行代码,特点是只执行一次
clearTimeout(代码,交互时间); //取消清除setTimeout的设置
案例1:逐个显示文字
代码:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>逐个显示文字</title>
<script language="JavaScript" type="text/javascript">
var str = "我要一个一个的显示出来";
var i= 0;
function scroll(){
var msg = str.substring(0,i+1);
document.getElementById('word').innerHTML=msg;
i++;
if(msg<str.length){i=0;}
}
setInterval("scroll()",1000);
</script>
</head>
<body>
<div id="word">
</div>
</body>
</html>
案例2:倒计时后跳转
代码:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>js定时跳转页面的方法</title>
</head>
<body>
<script type="text/javascript">
var tt=10;
function aa(){
document.getElementById('show').innerHTML=tt+"秒之后我就要跳转了";
tt--;
if (tt==0) {window.location.href="http://www.csdn.net";}
}
setInterval('aa()',1000);
</script>
<div id="show"></div>
</body>
</html>