/** 实现思路:
** 参数需要一个执行的频率,和一个对应的处理函数,
** 内部需要一个lastTime 变量记录上一次执行的时间
**/
function throttle (func, wait) {
let lastTime = null // 为了避免每次调用lastTime都被清空,利用js的闭包返回一个function确保不生命全局变量也可以
return function () {
let now = new Date()
// 如果上次执行的时间和这次触发的时间大于一个执行周期,则执行
if (now - lastTime - wait > 0) {
func()
lastTime = now
}
}
}
// 由于闭包的存在,调用会不一样
let throttleRun = throttle(() => {
console.log(123)
}, 400)
window.addEventListener('scroll', throttleRun)
function throttle (func, wait) {
let lastTime = null
let timeout
return function () {
let context = this
let now = new Date()
// 如果上次执行的时间和这次触发的时间大于一个执行周期,则执行
if (now - lastTime - wait > 0) {
// 如果之前有了定时任务则清除
if (timeout) {
clearTimeout(timeout)
timeout = null
}
func.apply(context, arguments)
lastTime = now
} else if (!timeout) {
timeout = setTimeout(() => {
// 改变执行上下文环境
func.apply(context, arguments)
}, wait)
}
}
}
debounce (func, wait) {
let lastTime = null
let timeout
return function () {
let context = this
let now = new Date()
// 判定不是一次抖动
if (now - lastTime - wait > 0) {
setTimeout(() => {
func.apply(context, arguments)
}, wait)
} else {
if (timeout) {
clearTimeout(timeout)
timeout = null
}
timeout = setTimeout(() => {
func.apply(context, arguments)
}, wait)
}
// 注意这里lastTime是上次的触发时间
lastTime = now
}
}
function debounce(method){
clearTimeout(method.timer);
method.timer=setTimeout(function(){
method();
},50);
}
var oldTime=new Date().getTime();
var delay=50;
function throttle1(method){
var curTime=new Date().getTime();
if(curTime-oldTime>=delay){
oldTime=curTime;
method();
}
}
var timer=undefined,delay=50;
function throttle2(method){
if(timer){
return ;
}
method();
timer=setTimeout(function(){
timer=undefined;
},delay);
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有