There are two types of timers in JavaScript: 1. Single timer, defined using the setTimeout() method, which can execute a code block once after the specified time (in milliseconds); 2. Loop timer, Use the setInterval() method to define certain codes to be executed repeatedly according to a specified period (in milliseconds).
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
In JavaScript, we can use timers to delay the execution of certain codes, or to repeatedly execute certain codes at fixed intervals. For example, you can use a timer to regularly update the ads on the page or display a real-time clock, etc.
JavaScript provides two timers: setTimeout() and setInterval()
Method | Description |
---|---|
setTimeout() | After the specified time (unit is milliseconds), execute certain codes. The code will only be executed once |
setInterval () | Repeatedly execute certain codes according to the specified period (unit: milliseconds). The timer will not stop automatically unless the clearInterval() function is called to manually stop or close the browser window |
setTimeout()
JS setTimeout() function is used to execute certain code after the specified time. The code is only executed once.
Usage:
setTimeout(code,millisec)
code Required. The string of JavaScript code to be executed after the function to be called.
#millisec Required. The number of milliseconds to wait before executing code.
Example:
setInterval()
JS setInterval() function can define a timer that can be executed repeatedly , each execution needs to wait for the specified time interval.
Usage:
setInterval(code,millisec[,"lang"])
code Required. A function to be called or a string of code to be executed.
#millisec Required. The time interval, in milliseconds, between periodic executions or calls to code.
Example:
[Recommended learning:javascript advanced tutorial]
The above is the detailed content of What are the timers in javascript. For more information, please follow other related articles on the PHP Chinese website!