咱們在進行搜索或則表單驗證的時候,用戶進行屢次輸入, 咱們通常採用最後一刻輸入完成的或者最後請求的響應數據。promise
這裏有兩種作法。markdown
無論事件觸發頻率多高,必定在事件觸發n
秒後才執行,若是你在一個事件觸發的 n
秒內又觸發了這個事件,就以新的事件的時間爲準,n
秒後才執行,總之,觸發完事件 n
秒內再也不觸發事件,n
秒後再執行。app
function debounce(event, time) {
let timer = null;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(()=> {
event.apply(this, args);
})
}
}
複製代碼
屢次觸發promise請求, 使用最後請求返回的數據.異步
function dehancePromise(axoisfn) {
let searchIndex = 0;
return ()=> {
let _searchIndex = searchIndex + 1;
searchIndex++;
return new Promise((resolve, reject)=> {
axoisfn().then((value)=> {
if (_searchIndex === searchIndex) {
resolve(value);
} else {
resolve({ msg: `not last promise${value}` });
};
})
})
}
}
let count = 0;
const axoisfn=(time=300)=>{
return new Promise((resolve, reject)=>{
setTimeout(()=>{
resolve(count++);
}, time)
})
}
const result = dehancePromise(axoisfn);
result().then((value)=>console.log(value));
result().then((value)=>console.log(value));
複製代碼
一、鏈式調用實現 this: 若是構造函數返回this或則返回當前所在函數的引用.函數
異步this: 每一個方法返回this串接全部this,建立一個異步隊列添加每一個方法註冊的fn. 這樣全部任務放到任務隊列裏面,經過一個 方法有序執行隊列裏面的任務.(通俗來講鏈式註冊和執行調用不在一個事件循環裏面)優化
function Person(name) {
return new Man(name);
};
function Man(name) {
this.task = [];
let fn = ()=>{
console.log(name)
this.next();
}
this.task.push(fn);
setTimeout(()=> {
this.next();
})
return this;
}
Man.prototype.firstWait = function(time) {
console.time("firstSleep");
let that = this;
let fn = ()=> {
setTimeout(()=>{
console.timeEnd('firstSleep');
that.next();
}, time)
};
this.task.unshift(fn);
return this;
}
Man.prototype.wait = function(time) {
console.time("Sleep");
let that = this;
let fn = ()=> {
setTimeout(()=>{
console.timeEnd('Sleep');
that.next();
}, time)
};
this.task.push(fn);
return this;
}
Man.prototype.eat = function(food) {
let that = this;
let fn = ()=>{
console.log(`eat: ${food}`);
that.next();
}
this.task.push(fn);
return this;
}
Man.prototype.next = function() {
let fn = this.task.shift();
fn && fn();
}
Person('Tony').eat('apple').wait(500).firstWait(1000);
複製代碼