


Examples to explain the usage of setTimeout() in JS_javascript skills
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.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use JS and Baidu Map to implement map pan function Baidu Map is a widely used map service platform, which is often used in web development to display geographical information, positioning and other functions. This article will introduce how to use JS and Baidu Map API to implement the map pan function, and provide specific code examples. 1. Preparation Before using Baidu Map API, you first need to apply for a developer account on Baidu Map Open Platform (http://lbsyun.baidu.com/) and create an application. Creation completed

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

How to use JS and Baidu Maps to implement the map heat map function Introduction: With the rapid development of the Internet and mobile devices, maps have become a common application scenario. As a visual display method, heat maps can help us understand the distribution of data more intuitively. This article will introduce how to use JS and Baidu Map API to implement the map heat map function, and provide specific code examples. Preparation work: Before starting, you need to prepare the following items: a Baidu developer account, create an application, and obtain the corresponding AP

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

How to use JS and Baidu Maps to implement map polygon drawing function. In modern web development, map applications have become one of the common functions. Drawing polygons on the map can help us mark specific areas for users to view and analyze. This article will introduce how to use JS and Baidu Map API to implement map polygon drawing function, and provide specific code examples. First, we need to introduce Baidu Map API. You can use the following code to import the JavaScript of Baidu Map API in an HTML file
