首页 > 技术文章 > 函数防抖-TS实现

alone4436 2021-07-19 23:07 原文

什么是函数防抖?

在事件被触发n秒后再执行回调,如果在这n秒内又被触发,则重新计时

实现很简单,大体就是设置一个变量来记录定时器,每次触发事件的时候就看定时器是否存在,如果存在清除一下,然后重新开启一个定时器。时间到了,定时器就执行了。

由于很好理解,直接上代码:

// index.html
<!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>Type Script in Action</title>
    <script src="/src/libs/global-lib.js"></script>
</head>
<body>
    <div class="app"></div>
</body>
</html>
// 脚本文件-使用了Jquery

import $ from "jquery";
$(".app").eq(0).css("width", "200px");
$(".app").eq(0).css("height", "200px");
$(".app").eq(0).css("background", "#ff6600");

$(".app").eq(0).on("mousemove", mouseMoveEvent);

let moveWatcher: null | number = null;

interface nodeEvent {
    target: {
        nodeName: string;
    };
    [key: string]: any;
}

function mouseMoveEvent(event: nodeEvent): void {
    if (moveWatcher) {
        clearTimeout(moveWatcher);
        moveWatcher = null;
    }

    moveWatcher = window.setTimeout(() => {
        console.log(event.target.nodeName);
    }, 1000);
}

到此结束,睡觉

 

推荐阅读