2015-03-28 18:08:52
通过JavaScript做定时器有两种方法:
第一种为不循环定时器:只出现一次,通过window.setTimeout(‘function_name();‘,timeout);方法
timeout为毫秒数,意为过timeout后,执行function_name();函数,window可省
<script language=‘javascript‘>
//定义一个函数,显示你好信息,要求该函数在页面加载5秒后被调用
function getHello(){
alert(‘你好‘);
}
window.setTimeout(‘getHello();‘,5000);
</script>
//例如:定义一个函数,要求将在页面上显示的图片换成另一张图片,该函数在3秒后被调用
<script language=‘javascript‘>
function changePic(){
document.images[0].src=‘2.jpg‘;
}
window.setTimeout(‘changePic();‘,3000);
</script>
</head>
<body>
<img src=‘1.jpg‘/>
</body>
第二种为可循环定时器:也就是只要过了那个时间就会出现一次,通过window.setInterval(‘function_name();‘,timeout);
循环定时器就是只要过了timeout毫秒后,函数体机会执行一次
/*定义4个字符串,要求在页面显示一个文本框,要求每隔3秒后在文本框随机显示已经定义好的四个字符串之一*/
<style>
#text1{
border:solid 1px;
}
</style>
<script>
var arr=new Array(‘Peter‘,‘Amy‘,‘Linda‘,‘Bob‘);
function getString(){
var index=Math.floor(Math.random()*arr.length);
text1.value=arr[index];
}
window.setInterval(‘getString();‘,3000);
</script>
</head>
<body topmargin=‘200px‘>
<center>
<input type=‘text‘ name=‘text1‘ id=‘text1‘/>
</center>
</body>
原文:http://www.cnblogs.com/xiaotudou-datudou/p/4374600.html