防抖(Debounce)和节流(Throttle)都是用来优化函数执行频率的技术,特别在处理用户输入、滚动等频繁触发的情况下,它们可以有效减少函数的执行次数,从而提升性能和用户体验。但它们的工作方式和应用场景有所不同。
1.防抖(Debounce)
防抖的主要思想是,当持续触发事件时,在事件最后一次触发之后,只有等待一段时间没有触发新事件,才会执行函数。简言之,防抖是将多次高频触发的事件合并成一次执行。
应用场景:适用于输入框输入、搜索框自动联想等情况。例如,在用户输入过程中,只在用户停止输入后的一段时间内才触发搜索操作。
2.节流(Throttle)
节流的思想是,当持续触发事件时,保证在一定时间间隔内执行一次函数。即使在该时间间隔内触发了多次事件,也只会执行一次函数。
应用场景:适用于滚动加载、页面滚动等情况。例如,在页面滚动过程中,只在一段时间间隔内触发一次加载更多的操作。
防抖实现示例:
// pages/index/index.js
Page({debounceInput: function (e) {const value = e.detail.value;this.debouncedSearch(value);},onLoad: function () {this.debouncedSearch = this.debounce(this.search, 300);},debounce: function (func, delay) {let timer;return function (...args) {clearTimeout(timer);timer = setTimeout(() => {func.apply(this, args);}, delay);};},search: function (value) {console.log("Searching for:", value);// 实际的搜索操作},
});
在这个示例中,我们使用了防抖技术来处理用户在输入框输入时的搜索操作。在 onLoad 阶段,我们创建了一个名为 debouncedSearch 的防抖函数,将实际的搜索操作 search 作为参数传递给它。当用户输入时,会触发 debounceInput 函数,它会调用 debouncedSearch 来触发搜索操作,但只有在用户停止输入一段时间后才会真正执行搜索。
节流实现示例:
// pages/index/index.js
Page({throttleScroll: function (e) {this.throttledLoadMore();},onLoad: function () {this.throttledLoadMore = this.throttle(this.loadMore, 1000);},throttle: function (func, delay) {let lastTime = 0;return function (...args) {const now = new Date().getTime();if (now - lastTime >= delay) {func.apply(this, args);lastTime = now;}};},loadMore: function () {console.log("Loading more data...");// 实际的加载更多操作},
});
在这个示例中,我们使用了节流技术来处理页面滚动时的加载更多操作。在 onLoad 阶段,我们创建了一个名为 throttledLoadMore 的节流函数,将实际的加载更多操作 loadMore 作为参数传递给它。当页面滚动时,会触发 throttleScroll 函数,它会调用 throttledLoadMore 来触发加载更多操作,但只会在一定时间间隔内执行一次。