
具体代码:
<html><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><title>无标题文档</title><script type="text/javascript">var timer; //全局变量var i=0; //变量初始化,全局变量//定义函数:开始计时function start(){ //获取id=result的对象 var obj = document.getElementById("result"); var str = "该程序已经运行了"+i+"秒!"; i++; //展开 i=i+1 //将变量str的内容写入到id=result中去 obj.value = str; //给表单元素加内容,一般用value属性//除表单外的其它标记用JS写内容,使用innerHTML//设置延时器 timer = window.setTimeout("start()",10);}//定义函数:停止计时function stop(){ window.clearTimeout(timer);}</script></head><body><input type="button" id="result" value="该程序已经运行了0秒!" /><br /><input type="button" onclick="start()" value="开始" /><input type="button" onclick="stop()" value="停止" /></body></html>下面来说一说具体的用法:<html><head><scripttype="text/javascript">functiontimedMsg(){vart=setTimeout("alert("5seconds!")",5000)}</script></head><body><form><inputtype="button"value="Displaytimedalertbox!"onClick="timedMsg()"></form><p>Clickonthebuttonabove.Analertboxwillbedisplayedafter5seconds.</p></body></html>3、实例(2)functionclockon(bgclock){varnow=newDate();varyear=now.getFullYear();varmonth=now.getMonth();vardate=now.getDate();varday=now.getDay();varhour=now.getHours();varminu=now.getMinutes();varsec=now.getSeconds();varweek; month=month+1;if(month<10)month="0"+month;if(date<10)date="0"+date;if(hour<10)hour="0"+hour;if(minu<10)minu="0"+minu;if(sec<10)sec="0"+sec;/*vararr_week=newArray("星期日","星期一","星期二","星期三","星期四","星期五","星期六");week=arr_week[day];*/switch(day){case1:week="星期一";break;case2:week="星期二";break;case3:week="星期三";break;case4:week="星期四";break;case5:week="星期五";break;case6:week="星期六";break;default:week="星期日";break;}vartime="";time=year+"年"+month+"月"+date+"日"+week+""+hour+":"+minu+":"+sec;if(document.all){bgclock.innerHTML="系统公告:["+time+"]"}vartimer=setTimeout("clockon(bgclock)",200);}4、执行var msg="1shaspassed!";此时不论是直接执行
setTimeout(alert(msg),1000);//alert(msg)会被立即执行还是
setTimeout(“alert(msg)”,1000);//系统报错msgisnotdefined(chrome)都不能达到预期的目的,因为定时器会努力地将code转化为一个function对象,第一个错例里定时器立即执行code希求返回一个function对象,结果扑了空;第二个虽然成功封装出function对象,但是定时器在msg的可见域外执行code,所以msg得不到正确的传递
var msg="1shaspassed!";setTimeout(function(){alert(msg);},1000);第一个参数传递了一个会调用所需语句的function对象,这样就解决了code带参的问题。