I. SUMMARY of previously
1) JavaScript is run in a single-threaded execution environment
2) The order in which events are scheduled to be executed by the browser
Second, setTimeout
Usage Scenario: Set code to execute at some time in the future, and the timing of execution is not guaranteed.
How you work: Insert time into the execution queue after a certain time has elapsed, note that it is not immediately executed
Three, repeat the timer setinterval
Usage scenario: Inserting a pending code in the code execution queue within a set time period
Note: This insertion is skipped when the code in the timer is executing
Disadvantage: Even if the execution of some interval code is skipped, when the timer code execution time is longer than the set time, the interval of code execution will still appear smaller than expected
Workaround: Link calls to settimeout instead of setinterval
SetTimeout (function () { //handling ... SetTimeout (Argument.callee, Time) }}, Time)
Iv. Examples of application scenarios
1) JavaScript in the browser is assigned a certain amount of resources, code beyond a specific time or a specific statement will not be executed, if the code is not synchronized, and can not be immediately executed, you can use the Timer Addend component block method to block execution, to solve the problems caused by the above limitations
2) Throttling: Some JS statements are consumed very large, such as Dom operation, when such a statement too many will cause the browser crashes, in order to solve the above problem, you can use settimeout to throttle the function, that is, the cost of the larger code can not be continuous execution without interruption
Take throttling as the window size changes:
Function throttle (method, context) {//when the second function is empty, the method is executed at the global scope cleartimeout (method.tid); Method.id = SetTimeout (function () { Method.call (context) }, +)}function resizeprocess = function () { // The actual code to execute when the window size changes }window.resize = function () { throttle (resizeprocess)}
Welcome to the Exchange!
A brief analysis of JavaScript timer settimeout and setinterval