A solution to the accumulation of animate animation in jquery

  • 2020-03-26 21:22:54
  • OfStack

Yesterday, one of my classmates asked me for help and said that they had made a simple animation effect, that is, the picture automatically played left and right
 
<span style="white-space:pre"> </span> 
var _left = 770; 
var left = -_left;//-770 
function slideImg() { 
if(left == -3080 || left == 0) { 
_left = -_left; 
} 
$('.slidepics').animate({'left': left + 'px'},1000); 
left = left - _left; 
tim = setTimeout(slideImg,5000); 
} 
slideImg(); 

 
 I looked at it. It was easy. At first glance, it didn't seem like a problem. Then he said something strange had been bothering him for a month. He said the window was at the front ok , but when you minimize the window or browse other Windows, it will appear a quick play, after a while it is normal again ( ie No problem, chrome There is a problem, firefox No problem).  

 Since I had never encountered this problem before, I also thought about it for more than half an hour, but I couldn't get it done. Then I looked through the notes I had made before and got the answer, that one setTimeout Animated queues are generated when used, possibly in chrome When the window in the browser is not at the front of the queue animation accumulation, when the return to the front of the burst out, then thought jquery In the stop Method that stops all animations on this element. Sure enough, add it ok the  

 
<span style="white-space:pre"> </span> 
var _left = 770; 
var left = -_left;//-770 
function slideImg() { 
if(left == -3080 || left == 0) { 
_left = -_left; 
} 
$('.slidepics').stop().animate({'left': left + 'px'},1000); 
left = left - _left; 
tim = setTimeout(slideImg,5000); 
} 
slideImg(); 

Related articles: