函数防抖
function ajax(content){
console.log(`ajax请求${content}`)
}
//ES6
function debounce(fn,delay){
return args =>{
clearTimeout(timer)
var timer = setTimeout(()=>{
fn(args)
},delay)
}
}
//ES5
function debounce(fn,delay){
return function(args){
let _this = this
let _args = args
clearTimeout(timer)
var timer = setTimeout(function(){
fn.call(_this,_args)
},delay)
}
}
let input = document.querySelector('#username')
let ajaxDebounce = debounce(ajax,1000)
input.addEventListener('keyup',function(e){
ajaxDebounce(e.target.value)
})
函数节流
function ajax(content){
console.log(`ajax请求${content}`)
}
//ES6
function throttle(fn,delay){
let lastime,timer
return args =>{
let now = new Date()
if(lastime && now < lastime+delay){
clearTimeout(timer)
var timer = setTimeout(args =>{
last = now
fn(args)
},delay)
}
else{
last = now
fn(args)
}
}
}
//ES5
function throttle(fn,delay){
let timerid,last
return function(args){
let _this = this
let _args = args
let now = new Date()
if(last && now < last + delay){
clearTimeout(timerid)
deferTimer = setTimeout(function () {
last = now
fun.apply(_this, _args)
}, delay)
}
else{
last = now
fn.call(_this,_args)
}
}
}
let input = document.querySelector('#username')
let ajaxThrottle = throttle(ajax,1000)
input.addEventListener('keyup',function(e){
ajaxThrottle(e.target.value)
})
手动实现call,apply
Function.prototype.callme = function(content){
content = content || window
let args = [...rest].slice(1)
content.say = this //this 等于某个对象的具体方法
//call
content.say(...args)
//apply
content.say(args)
}
手动实现promise
let p = new Promise((resolve,reject) =>{
resolve('成功')
})
p.then(res =>{
console.log(res)
})
class Promise{
constructor(executor){
this.status = 'pending';
this.value = null;
try{
executor(this.resolve.bind(this),this.reject.bind(this));
} catch(error){
this.reject(error)
}
}
resolve(value){
if(this.status === 'pending'){
this.status = 'fufilled'
this.value = value
}
},
reject(reason){
if(this.status === 'pending'){
this.status = 'rejected'
this.value = reason
}
},
then(onFulfilled, onRejected){
if(typeof onFulfilled != "function"){
onFulfilled = () =>{}
}
if(typeof onRejected != "function"){
onRejected = () =>{}
}
if(this.status === 'fufilled'){
onFulfilled(this.value)
}
if(this.status === 'rejected'){
onRejected(this.value)
}
}
}