JavaScript防抖實現

南易武痴發表於2020-12-24
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #container {
            width: 100%;
            height: 300px;
            background-color: rgb(13, 84, 105);
            color: #fff;
            font-size: 48px;
            text-align: center;
            line-height: 300px;
        }
    </style>
</head>

<body>

    <div id="container"></div>
    <script>
        let count = 0;
        let container = document.getElementById('container')

        function doSomething() {
            container.innerHTML = count++
        }
        //防抖
        function debounce(fn, wait, immediate) {
            let timeout, result
            let debounced = function () {
                // 解決this指向問題
                let context = this
                //函式引數
                let args = arguments
                //清楚定時器
                clearTimeout(timeout)
                if (immediate) {
                    //立即執行
                    let callNow = !timeout;
                    timeout = setTimeout(() => {
                        timeout = null
                    }, wait)
                    if (callNow) {
                    
                        result = fn.apply(context, args)
                    }
                } else {
                    timeout = setTimeout(function () {
                        result = fn.apply(context, args)
                    }, wait)
                }

            }
            // 取消
            debounced.cancel = function () {
                clearTimeout(timeout)
                timeout = null
            }
            return debounced
        }
        container.onmousemove = debounce(doSomething, 300, false)
    </script>
</body>

</html>

相關文章