This article mainly shares with you the method of implementing animation timer in JS. Broadly speaking: all visual presentations changed through JS are called animations; for example, interactive feedback of buttons, links and other elements. , in a narrow sense: the visual animation effect produced by continuously calling js functions through timers to change element attributes.
Timer is the core technology of JavaScript animation;
setTimeout(), setInterval() are well known to everyone and were often used in the past. ;
Usually they do something auxiliary and icing on the cake;
Careful people may find a phenomenon that there is a loop animation when switching from other tabs The page will have freezes and rapid frame switching;
The problem lies in their inner operating mechanism;
The first parameter It is recommended to use the function form, the string form will be parsed twice, and there is the same problem as eval;
There are more than two parameters, there can be more, see example 1;
This points to the problem, see example 2;
The return value is an integer;
clearTimeout(timer) cancels the timer;
setInterval ,clearInterval is the same as above;
Example 1:
setTimeout(function(a,b){ console.log(a+b); },1000,1,1);
Example 2:
var a = 0; function foo(){ console.log(this.a); }; var obj = { a : 2, foo:foo } setTimeout(obj.foo,100);
Example:
setTimeout(function(){ console.log(1); }); console.log(0);
Reason: Join the queue, blocking execution.
setTimeout legend:
setInterval legend:
##Existence is reasonablewindow.requestAnimFrame = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function( callback ){ window.setTimeout(callback, 1000 / 60); }; })();
JavaScript timer detailed explanation
Detailed analysis of Node timer
The above is the detailed content of JS implements animation timer method. For more information, please follow other related articles on the PHP Chinese website!