Project background

In a recent project, it is necessary to control the page movement according to the mouse wheel, and then generate different animations according to the distance of the page movement. However, when sliding very quickly, some animations will play other animations before the end, and the page scrolling is abnormal.

solution

  1. The first thing I want to do is to add an anti-shake to the mouse event, as follows:
$('body').mousewheel(function(ev,delta){
  clearTimeout(timer); 
  timer = setTimeout(function(){
    // Event processing
  },200)})Copy the code

However, it only solves the problem of abnormal page scrolling when sliding too fast

  1. As for the problem of playing other animations before the animation ends, I thought of setting a state to control optimization. As follows:
var scrolled = true
$('body').mousewheel(function(ev,delta){
  if(scrolled){
    scrolled = false
      clearTimeout(timer); 
      timer = setTimeout(function(){
        // After each animation is finished, other animations can be responded to
        $('html,body').animate({scrollTop: 0}, 'normal'."linear".function(){
          scrolled = true
        });
      },200)}})Copy the code

After the end of each animation or movement, scrolled is set to true to carry out the next response.