Contents of this section: SetInterval and SetTimeout One, SetInterval () define and use the SetInterval () method to execute a function or expression according to the specified period (in milliseconds). The method keeps looping through the function 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 (). Syntax SetInterval (code,millisec[, "Lang"]) code required. The function to invoke or the code string to execute. Millisec must. The time interval, in milliseconds, between periodically executing or calling code. Returns a value that can be passed to Window.clearinterval () to suppress periodic execution of code. Example:
-
- Stop interval Events
Copy CodeSecond, the setTimeout () definition and usage the SetTimeout () method is used to call a function or evaluate an expression after a specified number of milliseconds, unlike the SetInterval () method, which is executed only once. Syntax settimeout (CODE,MILLISEC) code required. The JavaScript code string to execute after the function to invoke. Millisec required. The number of milliseconds to wait before executing the code, in milliseconds. Tip: (1) setTimeout () Although the code executes only once. However, if you want to call multiple times, in addition to using setinterval () You can also let the executed code inside itself again call the SetTimeout () method has reached the goal of multiple executions. (2) Another settimeout () method can also return an ID value to facilitate the cancellation of the use of the SetTimeout () method with the Clearinterval () method. Example:
-
Copy CodeFor the two methods of SetInterval and settimeout, it is important to note that if you are required to perform an action precisely after every fixed interval, it is best to use setinterval, and if you do not want to cause mutual interference due to successive calls, In particular, each time a function call requires heavy computation and a long processing time, it is best to use settimeout. |