The use of "throttle valve" in the carousel

       The use of the throttle valve in JavaScript can be combined with  the content of the carousel in the previous article  . There are two play buttons on the left and right in the carousel. The faster the click, the faster the playback. Before a picture is finished, the next picture starts to be played, and we have no time to see what the content of the picture is, so there is a throttle for this.

The function of the throttle valve: When the animation function of the previous picture is executed, the button can be clicked again to play the next picture, and the event cannot be triggered continuously


Use of throttle valve:

The use of the throttle valve is very simple. We need to give it a global variable, such as flag, and assign it to true. When we click the button, we first judge that only true can execute the animation function. After we click it once, we immediately set it to The variable is overwritten to false, so that it cannot be triggered continuously. Some people will ask, but isn't it possible to click once and never click again? ? Yes, to solve this problem, we use the third parameter in our animation function ------- the callback function. Friends who don't know what the callback function is can click into my article to explain: Callback function  , we know that if there is a callback function, it will be triggered after the animation is completed, so we can change our flag value to true in this callback function.

Here we only use the click event of the button on the right to explain:

The code here is to click the button on the right, and the same is true for the button on the left

 flag=true;    //定义变量
    rightbtn.addEventListener('click',function(){
        if(flag==true){   //点击后判断,只有为true 才能执行
            flag=false;    //判断后立马重新赋值为flase
            if(num==circleul.children.length-1){
                circleul.style.left=0;
                num=0;
            }
            num++;
            long=num*windows.offsetWidth-6*num;
            run(circleul,-long,function(){   //添加了回调函数
                flag=true;   //动画函数执行完后 重新赋值为true
            });
        //小圆圈跟着一起变化
            circlechange++;
            if(circlechange==circleul.children.length-1){
               circlechange=0;
            }
            for(var i=0;i<circleol.children.length;i++){
                 circleol.children[i].className='';
            }
            circleol.children[circlechange].className='circlecolor';
        }
    })

This is how we use the callback function, add a variable to control, and complete the locking animation function and unlocking animation function step by step, like a throttle valve?

Guess you like

Origin blog.csdn.net/weixin_52212950/article/details/123902867