Javascript’s setTimeOut and setInterval functions are widely used. They are used to handle delayed and scheduled tasks. For example, a login box pops up after opening a web page for a period of time, and the page sends asynchronous requests to obtain the latest data at regular intervals, etc. But their applications are different.
The setTimeout() method is used to call a function or calculated expression after a specified number of milliseconds, while setInterval() loops to call a function or expression every specified number of milliseconds until clearInterval clears it. In other words, setTimeout() is only executed once, and setInterval() can be executed multiple times. The parameters of the two functions are also the same. The first parameter is the code or handle to be executed, and the second parameter is the number of milliseconds to delay.
setTimeOut usage
The usage of the setTimeout function is as follows:
timeoutID: timer ID number, which can be used to clear the timer in the clearTimeout() function.
func: the function being executed.
code: (alternative syntax) a string of code to be executed.
delay: delay time, in milliseconds. If not specified, defaults to 0.
We can use window.setTimeout or setTimeout. The two writing methods are basically the same, except that window.setTimeout refers to the setTimeout function as a property of the global window object.
Application example:
When the code is executed, the timeout() function will be called after 5 seconds. Click to see the demonstration.
setInterval usage
The parameters and usage of the setInterval function are the same as the setTimeout function. Please refer to the usage introduction of the setTimeout function above. The difference is that setInterval executes the func or code code at regular intervals.
Application example:
The function timego() defines the content displayed by the page element #tt. When tt equals 0, the page is directed to the home page. Then we define a timer timer and use setInterval() to call timego() every 1 second. In this way, timego will be executed 10 times, and each time the number tt will be reduced by 1 until it is 0. Then if you want to stop the timer, you can use the following code:
When the code is executed, the page will jump to the homepage after 10 seconds
In fact, setTimeout() can also execute a function repeatedly at regular intervals, but we still simply use setTimeOut and setInterval differently. In addition, JavaScript runs in the browser's JavaScript engine in a single-threaded manner. In actual applications, complex tasks need to be queued for execution, which may lead to inaccurate timers. This issue needs to be considered in large-scale applications. This article does not Do deep research.
The above is the entire content of this article, I hope you all like it.