Examples of usage of setInterval and setTimeout in js

WBOY
Release: 2016-07-25 09:12:47
Original
1116 people have browsed it

Contents of this section: setInterval and setTimeout

1. Definition and usage of setInterval() The setInterval() method executes a function or expression at a specified period in milliseconds. This method will continue to call the function in a loop until the function is explicitly stopped using clearInterval() or the window is closed. The parameter of the clearInterval() function is the ID value returned by setInterval(). grammar setInterval(code,millisec[,"lang"]) code is required. A function to be called or a string of code to be executed. millisec is required. The time interval, in milliseconds, between periodic executions or calls to code. return value A value that can be passed to Window.clearInterval() to cancel periodic execution of code.

Example:

  1. Stop interval event
Copy code

2, setTimeout() definition and usage The setTimeout() method is used to call a function or calculated expression after a specified number of milliseconds. The difference between this method and the setInterval() method is that this method is only executed once.

Grammar setTimeout(code,millisec) code is 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 the code, in milliseconds. hint: (1) Although setTimeout() only executes the code once. But if you need to call it multiple times, in addition to using setInterval(), you can also let the executed code itself call the setTimeout() method again to achieve the purpose of multiple executions. (2) In addition, the setTimeout() method can also return an ID value to facilitate the use of the clearInterval() method to cancel the use of the setTimeout() method.

Example:


  1. If you want to execute an action accurately and then use setInterval, it is best to use setInterval. If you do not want to cause mutual interference due to continuous calls, especially if each function call requires heavy calculations and long processing time, then it is best to use setTimeout.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template