Never forget there will be memories

preface

As we all know, there are two kinds of JS timers, setTimeout and setInterval, and requeTanimationFrame has been added to the list of things that interviews often look at, so I’ll start with what to use, how to use it, and when to use it. What’s the difference between them and how do they relate to each other

1. SetTimeout

SetTimeout is a property of window. Since window is a global scope, we usually omit it when writing

The setTimeout() method is used to specify that a function or string will be executed after a specified number of milliseconds. It returns an integer indicating the timer number, which can be passed to clearTimeout() to cancel the function

SetTimeout takes two arguments. The first argument is function: indicates the function or code to be executed. The second argument is delay. If omitted, execute immediately

Under IE9, setTimeout is only allowed to take two arguments

Ie9 can have multiple parameters

There is also a third parameter that is not commonly used:

This is how it is interpreted in MDN

Clear the setTimeout method: setTimeout() corresponds to clearTimeout(id);

2. SetInterval (timer)

SetInterval is also a window method, window is omitted

The setInterval() method repeatedly calls a function or executes a code segment, with a fixed time delay between calls.

Each call has a fixed interval and returns an interval ID that uniquely identifies the interval and is called to clear when the timer is cleared.

Similarly, setInterval and setTimeout have the same three parameters

Function code delay arg1,… ArgN is optional and I won’t repeat it here

Method of clearing timer:

SetInterval () corresponds to clearInterval(id);

One quick question: What are the downsides of setInterval?

1. Don’t care if the callback function is still running. In some cases, the function may take longer than the interval to complete execution. For example, using setInterval to poll remote servers every 5 seconds, network latency, server unresponsiveness, and other factors will prevent requests from being fulfilled on time. This results in an unnecessary queue of requests being returned. 2. Ignore errors For some reason, setInterval calls code with an error, but instead of stopping execution, the code continues to execute the wrong code. 3. Inflexibility Aside from the drawbacks mentioned earlier, I would really like the setInterval method to have a parameter indicating how many times it should be executed rather than just executing endlessly.

3. RequeTanimationFrame (Animation API)

This is something THAT I discovered when I was reviewing for the interview how does MDN explain this API

Tell the browser window. RequestAnimationFrame () – you want to perform an animation, and required the browser until the next redraw calls the specified callback function to update the animation. This method takes as an argument a callback function that executes > before the browser’s next redraw.

Returns a callback argument to the function called to update the animation frame before the next redraw. The callback function is passed the DOMHighResTimeStamp parameter, which has the same return value as performing.now () and represents the time when requestAnimationFrame() started executing the callback function.

This means that requeTanimationFrame requires no time interval. Most computer monitors refresh at 60 Hz, which is equivalent to about 60 redraws per second. Most browsers limit redraws. So the optimal loop event is 1000ms/60, which is approximately 16.6ms

Features: RequestAnimationFrame collects all the DOM operations in each frame in a single redraw or redraw, and the redraw or redraw interval closely follows the browser’s refresh rate in hidden or invisible elements. RequestAnimationFrame will not be redrawn, which means less CPU, GPU and memory usage. RequestAnimationFrame is a browser API that optimizes method calls at runtime. And if the page is not active, the animation will automatically pause, saving CPU overhead. Official website Document address

4. When will these three methods be applied

SetTimeout is used to delay the execution of a method or function. SetInterval is generally used to refresh forms. For some forms, the refresh synchronization is specified in real time

5. Difference between setInterval and setTimeout

1. SetTimeout Stops when used once after the specified time. SetInterval repeats for the specified time

2. The two timer clearing methods are different setInterval() corresponds to clearInterval(id); SetTimeout () corresponds to clearTimeout(id);

6. Use setTimeout to implement setInterval

Principle:

The setTimeout method is called again when function is called inside setTimeout to achieve the effect of setInterval

Code implementation: Simple version:

setTimeout(function(){

     //do something 

     setTimeout(arguments.callee,interval);

},interval)
Copy the code

Complex version:

Function interval (func, w, t) {var interv = function () {if typeof (t = = = “undefined” | | t – > 0) {setTimeout (interv, w); try{ func.call(null); } catch(e){ t = 0; throw e.toString(); }}}; setTimeout(interv, w); }; Interval has an internal function called Inter, which is automatically called with setTimeout. In Inter there is a closure that checks the number of repetitions, calls the callback, and calls Interv again with setTimeout. If an exception occurs in a callback function, the interv call terminates and the exception is thrown. Of course there is no guarantee that the function will execute at a fixed interval, but it does guarantee that the function in the previous interval will have finished executing when the new interval starts, which I think is very important.

So the question is, what’s the difference between using setTimeout and setInterval

SetTimeout (fn, time), called when the time is greater than or equal to time; SetInterval (fn, time) is called intermittently, every other time. The timer created with setInterval() ensures that the timer code is inserted regularly into the queue. Here’s the problem: If the timer code doesn’t finish executing before the code is added to the queue again, the result is that the timer code runs several times in a row. And there’s no gap between them. Fortunately, the javascript engine is smart enough to avoid this problem. The timer code is added to the queue if and only if there is no how-code instance of the timer. This ensures that the minimum interval between the timer code joining the queue is the specified time. There are two problems with this repeat timer rule:

  1. Certain intervals will be skipped 2 multiple timer code execution times may be smaller than expected.