函数节流
这个词的产生呢?由于呢?某些事件会不停的触发执行,比如说scroll
这个事件,当我们滚动滑轮的时候,会不停的触发监听滚动事件,这个不是我们想要的。极大的浪费了运行性能,因此节流的思想应运而生。当然,这个是我个人的想法。在我看来,函数节流
就是用来解决无法阻止的不停触发的事件的。
节流的思想 由于某些事件将不停的触发,我们需要在某个事件来阻止其触发,需要借助定时器来解决这个问题。让这个函数在指定的时间段内触发,换句话来说就是让事件在过了某一时刻才触发。
function throttle(method, context) {
// 出入函数添加对象
// 函数调用,清空定时器
clearTimeout(method.tId);
// 给调用者定义一个定时器
method.tId = setTimeout(function() {
// 保留该函数的上下文,并调用
method.call(context);
}, 200);
// 200ms 为间隔时间
}
输入框:<input type="text" id="txt1">
function getKey(e) {
// 这里的e就是事件函数中的e
// this为事件事件对象
console.log('我执行了')
}
document.querySelector('#txt1').onkeyup = function(){
throttle(getKey, this);
}
在看一个demo
// 这里写原生js html,bdoy的高度设置为3000
document.addEventListener('scroll',function(e){
// 判断浏览器是否滚动到地步的逻辑
// console.log(e.target.body.offsetHeight)
let pageHeight = e.target.body.offsetHeight;
// body 总高度3000
let scrollTop = document.scrollingElement.scrollTop;
// 滚动高度。 变量
console.log(scrollTop);
let winHeight = window.innerHeight;
// 获取浏览器窗口的高度
// 浏览器窗口高度821
console.log(window.innerHeight);
//定义一个阀值
let thresold = pageHeight - scrollTop - winHeight;
// 进行判断
if (thresold > -100 && thresold <= 20) {
console.log('到底了');
}
})
```js
// 这个定义的函数需要在上面的那个函数中去被调用
function throttle(fn, interval = 500){
// 设置节流阀
let canRun = true;
return function () {
// 判断这个节流阀是否为true 。
if (!canRun) return ;
// 如果为true,进来之后,设置为false
canRun = false;
// 设置一个300毫秒的定时器
setTimeout(() => {
// 改变this指向
fn.apply(this,arguments);
// 在执行之后,在将节流阀值设置为true
canRun =true;
}, interval);
}
}
apply
,call
的用法哦。我是一个对前端非常感兴趣的小伙伴,如果你也是,可以加我为好友哦!
原文:https://www.cnblogs.com/yaogengzhu/p/10822489.html