JS

您所在的位置:网站首页 inputinfo函数 JS

JS

2023-03-14 03:27| 来源: 网络整理| 查看: 265

本文共 841 字,大约阅读时间需要 2 分钟。

前言

在进行页面窗口的resize、scroll、输入框内容校验等操作时,如果事件处理函数调用的频率无限制,会加重浏览器的负担,导致用户体验非常糟糕。此时我们可以采用debounce(防抖)和throttle(节流)的方式来减少调用频率,同时又不影响实际效果,这篇文章将主要分析函数节流。 详情参考:https://timor419.github.io/2020/08/08/JS-throttle/

介绍

函数节流:

当持续触发事件时,保证一定时间段内只调用一次事件处理函数。

实现原理:

当触发事件的时候,我们设置一个定时器,再次触发事件的时候,如果定时器存在,就不执行,直到delay时间后,定时器执行执行函数,并且清空定时器,这样就可以设置下个定时器。

适用场景:

输入框内容校验、页面滚动请求数据等。

JS代码: let timeout;// 函数节流  throttle(func, thres) {    const threshhold = thres || 200;// eslint-disable-next-line consistent-returnreturn function () {  clearTimeout(timeout);  timeout = setTimeout(() => {    if (func) {  func();}  }, threshhold);};  },  // 输入信息  inputInfo(e) {    const searchKey = e.detail.value;const func = () => {  this.setInput(searchKey);};this.throttle(func)();  },  // 网络请求  setInput(searchKey) {    console.log('网络请求', searchKey);  }, 最终效果

在这里插入图片描述

转载地址:https://blog.csdn.net/weixin_43937466/article/details/107881899 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3