Home >Web Front-end >JS Tutorial >A brief discussion on JavaScript function throttling_Basic knowledge
Some calculations and processing in the browser are much more expensive than others. For example, DOM operations require more memory and CPU time than non-DOM interactions. Attempting to perform too many DOM-related operations in succession can cause the browser to hang and sometimes even crash. This is especially likely to happen when using the onresize event handler in IE. When the browser is resized, the event is triggered continuously. If you try to perform DOM operations inside the onresize event handler, its high frequency of changes may crash the browser.
The basic idea behind function throttling is that certain code cannot be executed continuously and repeatedly without interruption. The first time the function is called, a timer is created to run code after a specified interval. When this function is called a second time, it clears the previous timer and sets another one. If the previous timer has already been executed, this operation has no meaning. However, if the previous timer has not yet been executed, it is actually replaced with a new timer. The purpose is to execute the function only after the request to execute it has been stopped for some time.
Application examples:
Suppose there is a element that needs to keep its height equal to its width. It can be encoded as follows: