js 节流函数封装示例

编程入门 行业动态 更新时间:2024-10-26 02:36:27

js 节流函数封装<a href=https://www.elefans.com/category/jswz/34/1770116.html style=示例"/>

js 节流函数封装示例

<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>节流函数示例</title><divstyle="width: 400px;height: 400px;background-color: red;font-size: 30px; text-align: center; line-height: 200px;"></div>
</head><body><script>const throttle = function (fn, delay) {let timer = null;return function () {if (!timer) {timer = setTimeout(() => {fn.apply(this, arguments);timer = null;}, delay);}};};const test = function (name) {let count = 0;return throttle(function () {document.querySelector('div').innerHTML = name + count++;}, 400);};document.querySelector('div').addEventListener('mousemove', test('张三'))</script></body></html>

可能存在的难点:为什么返回一个function? 答:因为入参是个fn,你得把返回值也写成一个函数。
为什么清除定时器要用timer=null,不用clearTimeout?答:因为清除定时器的时机是三秒后,只能写在定时器内,而clearTimeout只能定时器外部调用,所以用null。

更多推荐

js 节流函数封装示例

本文发布于:2023-12-04 11:25:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1660761.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:示例   函数   js

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!