码迷,mamicode.com
首页 > Web开发 > 详细

JS 防抖节流简单应用

时间:2021-03-08 14:01:59      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:ons   listen   rand   fun   initial   结果   class   add   name   

<!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>
</head>

<body>
    <input id="input" type="text">
    <button id="button">click</button>
    <script>
        function debounce(fun, delay) {
            let timer;
            return function (args) {
                clearInterval(timer)
                timer = setTimeout(() => {
                    fun(args)
                }, delay);
            }
        }
        function inputFun(value) {
            console.log(`你的输出结果是${value}`)
        }
        const input = document.getElementById("input")
        const deboundInput = debounce(inputFun, 500)
        input.addEventListener(‘keyup‘, function (e) {
            deboundInput(e.target.value)
        })
        function throttle(func, wait) {
            let timerOut;
            return function () {
                if (!timerOut) {
                    timerOut = setTimeout(function () {
                        timerOut = null;
                        func()
                    }, wait)
                }
            }
        }
        function handle() {
            console.log(Math.random())
        }
        document.getElementById("button").onclick = throttle(handle, 2000)
    </script>

</body>

</html>

JS 防抖节流简单应用

标签:ons   listen   rand   fun   initial   结果   class   add   name   

原文地址:https://www.cnblogs.com/lceihen/p/14495084.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!