JS常见方法 ----- 函数节流

防抖和节流

节流 就是 保证在一段时间内只执行一次核心代码(比如我连续的进行一些dom操作可能会会导致浏览器挂起)
背后的思想:某些代码不可以在没有间断的情况下连续重复执行。第一次调用函数,创建一个定时器在指定时间后执行,第二次调用函数的时候,会清除定时器并创建另一个定时器。 目的是只有在执行函数的操作请求 在定制了一段时间后再请求。

这是js高级程序设计的一段代码

function throttle (method, context) {
	clearTimeOut(method.id)
	method.id = setTimeout(function() {
		method.call(context)
	}, 500)
}
function (fn, delay = 200) {
	let canRun = true 
	return (..args) => {
		if(!canRun) return false
		canRun = false
		setTimeOut(()=> {
			fn.call(this, ...args)
			canRun = true
		},delay)
	}
}
function throttle = function (fn,  threshhold) {
	var last //记录上次执行的时间
	var timer //定时器
	return function () {
		let context = this
	    var args = argument
	    var now  = + new Date()//不懂为什么 
	    if(last && now < last + threshhold) {
	    	clearTimeout(timer)
	    	timer = setTimeout(function () {
	    		last = now
	    		fn.apply(context, argument)
			}, threshold)
	    } else {
			last = now
    		fn.apply(context, argument)
		}
	}
}
function throlle(fn, delay, option) {
	let prev = 0, context, args,timeout
	var later = function() {
			prev = optins.leading == false ? 0 : Date.now()
			fn.apply(context, args)
		}
	return function() {
		context = this
		args = arguments
		
		let now = Date.now()
		if(prev == 0 && !options.leading) prev = now
		let remain = delay - (now - prev)
		if(remain <=0) {
			if(timeout) {
				clearTimeout(timeout)
				timeout = null
			}
			fn.apply(context, args)
			prev = now
		} else if(!timeout && option.training) {
			timeout = setTimeout(later, remian)
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值