This article explains the usage of setTimeout() in JS with examples and shares it with everyone for your reference. The specific content is as follows
Rendering:
Specific code:
<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>
Let’s talk about the specific usage:
1. Parameters
code (required): (The original meaning is code) The JavaScript code string to be executed after the function to be called.
millisec (required): The number of milliseconds to wait before executing code.
Tips:
setTimeout() only executes code once. If you want to call it multiple times, use setInterval() or have the code itself call setTimeout() again.
2. Example
<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. Example (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. Execution
We often encounter a situation where the code in setTimeout(code, millisec) contains formal parameters,
For example: the information we need to prompt to the user after 1 second is stored in the variable msg,
var msg='1shaspassed!';
At this time, whether it is executed directly
setTimeout( alert(msg),1000);//alert(msg)会被立即执行
or
setTimeout(“alert(msg)”,1000);//系统报错msgisnotdefined(chrome)
Neither of them can achieve the expected purpose, because the timer will work hard to convert the code into a function object. In the first error case, the timer immediately executes the code and hopes to return a function object, but the result is in vain; in the second error example, although The function object is successfully encapsulated, but the timer executes code outside the visible domain of msg, so msg cannot be delivered correctly
The recommended solution is to use anonymous function callbacks
var msg='1shaspassed!'; setTimeout(function(){ alert(msg); },1000);
The first parameter passes a function object that will call the required statement, thus solving the problem of code with parameters.
The above is the entire content of this article. I hope it will be helpful to everyone in learning javascript programming.