Throttle - mouse follow effect example

Throttling strategy: As the name suggests, it can reduce the trigger frequency of events for a period of time.

It’s like launching a skill in a game. After Diao Chan’s first skill is used, if the cooldown is not good, there is no way to trigger the skill if you click it again. Anti-shake is like returning to the city. It can be interrupted but you can return to the city again. The last time you return city. Throttling is performed the first time it is triggered, while anti-shake is performed the last time it is triggered.

 Full code:
 

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./lib/jquery.js"></script>
    <style>
        html,
        body {
            margin: 0;
            padding: 0;
            overflow: hidden;
        }
        
        #ag {
            position: absolute;
        }
    </style>
</head>

<body>
    <img src="../angel.gif" alt="" id="ag">
    <script>
        // 获取小天使元素
        var angle = $('#ag');
        // 定义一个节流阀
        var timer = null;
        // 监听鼠标移动事件
        $(document).on('mousemove', function(e) {
            // 判断是否有节流阀
            if (timer) {
                return;
            }
            // 开启延时器
            timer = setTimeout(function() {
                angle.css('left', e.pageX + 'px').css('top', e.pageY + 'px');
                console.log(111);
                // 重置timer
                timer = null;
            }, 16)
        });
    </script>
</body>

</html>

Guess you like

Origin blog.csdn.net/qq_43781887/article/details/126921416