节流防抖
function debounce(func, delay = 300) {
let timer = null;
return function (...arg) {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
func.applay(this, ...arg);
}, delay)
}
}
let input = document.querySelector('input');
input.oninput = debounce(function () {
console.log(this.value);
}, 500);
function throttle(func, delay = 300) {
let flag = true;
return function (...arg) {
if (flag) {
setTimeout(() => {
func.apply(this, arg);
flag = true;
}, delay)
}
flag = false;
}
}
window.onscroll = throttle(function(){
console.log(123);
},500)
发布订阅模式
class EventEmitter {
constructor() {
this.event = {};
}
$on(eventName, callback) {
this.event[eventName] = this.event[eventName] || [];
this.event[eventName].push(callback);
}
$off(eventName, callback) {
this.event[eventName] = this.event[eventName].filter((itme) => { itme !== callback });
}
$emit(eventName, data) {
this.event[eventName].forEach(callback => {
callback(data);
});
}
}
const event = new EventEmitter();
const func1 = data => {
console.log('我是订阅事件1', data);
}
const func2 = data => {
console.log('我是订阅事件2', data);
}
const func3 = data => {
console.log('我是订阅事件3', data);
}
event.$on('key1', func1);
event.$on('key1', func2);
event.$on('key3', func3);
event.$emit('key1', '哈哈');
event.$emit('key1', '嘻嘻');
event.$emit('key3', '哈哈 嘻嘻');
call、apply和bind
Function.prototype.myCall = function (context, ...args) {
context = context || window;
let key = Symbol();
context[key] = this;
const result = context[key](...args);
delete context[key];
return result;
}
Function.prototype.myApply = function (context, args) {
context = context || window;
let key = Symbol();
context[key] = this;
const result = context[key](...args);
delete context[key];
return result;
}
Function.prototype.myBind = function (context, ...boundArgs) {
const orgFunc = this;
return function (...newArgs) {
const mergeArgs = [...boundArgs, ...newArgs];
orgFunc.apply(context, mergeArgs);
}
}
Promise.all() Promise.race()
Promise.myCall = function (prmoises) {
return new Promise((resolve, reject) => {
if (!Array.isArray(prmoises)) {
reject(new TypeError('参数必须为数组形式'));
}
let results = [];
let count = 0;
promises.forEach(promise, index => {
Promise.resolve(promise)
.then((result) => {
results[index] = result;
count++;
if (count === prmoises.length) {
resolve(results);
}
})
.catch((error) => {
reject(error);
})
});
})
}
Promise.myRace = function (promises) {
return new Promise((resolve, reject) => {
if (!Array.isArray(prmoises)) {
reject(new TypeError('参数必须为数组形式'));
}
promises.forEach((promise) => {
Promise.resolve(promise)
.then((result) => {
resolve(result);
})
.catch((error) => {
reject(error);
});
})
})
}