防抖和节流
节流 就是 保证在一段时间内只执行一次核心代码(比如我连续的进行一些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)
}
}
}