We often use setInterval or setTimeout to modify DOM and CSS for animation.

Animation realized by seTimeout will appear stutter and shake on some low-end machines. There are two reasons for this phenomenon:

  • The execution time of setTimeout is not fixed. In Javascript, the setTimeout task is put into an asynchronous queue. Only after the main thread is finished, the task in the queue will be checked to see whether the task needs to be executed. Therefore, the actual execution time of setTimeout is usually later than the set time.
  • The refresh frequency is affected by the screen resolution and screen size, so the refresh frequency may be different for different devices. SetTimeout can only set a fixed interval, which may not be the same as the refresh time of the screen.

However, requestAnimationFrame can also be used to implement animations

The requestAnimationFrame approach has the following advantages:

1. Optimized by browser, the animation is smoother

2. If the window is not activated, the animation will stop, saving computing resources

3. Save more power, especially for mobile terminals

The biggest advantage of requestAnimationFrame is

It is up to the system to decide when to execute the callback function. To be more specific, if the screen refresh rate is 60Hz, the callback function is executed every 16.7ms, if the refresh rate is 75 hz, the interval becomes 1000/75=13.3ms, in other words, the requestAnimationFrame moves at the pace of the system refresh. It ensures that the callback function is executed only once in each screen refresh interval, thus avoiding frame loss and animation stuttering.

Implement a div slide animation, from fast to slow 5s end

.sj{ width:50px; height:50px; border:1px solid red; position:absolute; <div class="sj" id="sj"></div> Var ele = document.getelementbyid ('sj') function animate(ele, SPD){var start = date.now (); // remember start time var timer = setInterval(function() { var timePassed = Date.now() - start; var step = Math.ceil(Math.abs(timePassed - 5000)/10) console.log(step) if (timePassed >= 5000) { clearInterval(timer); // finish the animation after 2 seconds return; } ele.style.left = ele.offsetLeft + step + 'px' }, spd); }Copy the code

Implement a div slide animation that goes from fast to slow to 500px

function animate1(ele,target,spd){ var timer = setInterval(function() { var step = (target-ele.offsetLeft)/10; Step = step>0? Step = step>0? Math.ceil(step):Math.floor(step); Ele.style. left = ele.offsetleft + step + "px"; If (math.abs (target-ele.offsetleft)<= math.abs (step)){ele.style.left = target + "px"; clearInterval(timer); } }, spd); }Copy the code