沒任務就停止,有任務就依序執行的小功能分享

沒任務就停止,有任務就依序執行的小功能分享

更新於 發佈於 閱讀時間約 4 分鐘

使用場景

在網路速度有限的情況下,依序記錄不斷產生的資訊,能統計使用者在頁面上操作了哪些功能。

依序執行不斷產生的任務

依序執行不斷產生的任務


實現過程

打造一個類別(Executor),裡面有一個對外函式(recordData),會把使用者加入的任務不斷加入陣列內。這裡為了方便,讓使用者傳入字串,自動把字串變成過兩秒會印在console的任務函式。

class Executor {
constructor() {
this.pendingFunctionArray = [];
}

recordFunction = async (string) => {
await new Promise((resolve) => setTimeout(resolve, 2000));
console.log(`${string} finish`);
};

recordData = (string) => {
this.pendingFunctionArray.push(() => recordFunction(string));
}
}


加入一個函式,裡面有個回圈會依序執行任務。每次使用者呼叫recordData加入任務,就會呼叫這個函式,讓這個函式不斷執行,直到任務完成後停止。

class Executor {
constructor() {
this.pendingFunctionArray = [];
}

recordFunction = async (string) => {
await new Promise((resolve) => setTimeout(resolve, 2000));
console.log(`${string} finish`);
};

recordData = (string) => {
this.pendingFunctionArray.push(() => recordFunction(string));
this.scheduleTasks();
};

scheduleTasks = async () => {
while (true) {
if (this.pendingFunctionArray.length == 0) break;

const recordFunction = this.pendingFunctionArray.shift();
await recordFunction();
}
};
}


但這樣會產生多個scheduleTasks函式同時執行,可能產生預期外的結果。可以加入一個參數isExecuting來判斷,確保只有一個scheduleTasks函式在執行。

class Executor {
constructor() {
/**@type {Function[]} 待處理陣列 */
this.pendingFunctionArray = [];
/**是否正在排程執行任務 */
this.isExecuting = false;
}

recordFunction = async (string) => {
await new Promise((resolve) => setTimeout(resolve, 2000));
console.log(`${string} finish`);
};

recordData = (string) => {
this.pendingFunctionArray.push(() => recordFunction(string));
this.scheduleTasks();
};

scheduleTasks = async () => {
if (this.isExecuting) return;

this.isExecuting = true;
while (true) {
if (this.pendingFunctionArray.length == 0) {
this.isExecuting = false;
break;
}

const recordFunction = this.pendingFunctionArray.shift();
await recordFunction();
}
};
}


最後附上在線demo的鏈接:依序執行不斷產生的任務

avatar-img
s_SoNg的沙龍
4會員
11內容數
留言
avatar-img
留言分享你的想法!
s_SoNg的沙龍 的其他內容
在工作上遇到nodejs呼叫執行檔執行失敗問題,最後發現是由於nodejs專案本身有用nssm包成服務,在服務環境的nodejs呼叫的執行檔也執行在服務中,造成程式不會跳出視窗而導致失敗。
準備專案 這邊首先準備一個新的專案,可以參考react官網,完成後參考README.md輸入npm run dev就可以啟動並在瀏覽器看到畫面 準備nssm工具 在google上搜nssm,第一個項目點進去後,找到並下載穩定版,附上下載鏈接 壓縮檔下載完畢後,解壓縮到喜歡的地方,然後進入資料
如果有個算法是2秒以上很耗時的長任務,希望在執行長任務前後修改state渲染loading畫面,可能會難以達到預期效果,會看到loading畫面一閃而過。 把setState改非同步的方法...
4/5React await setStat
在工作上遇到nodejs呼叫執行檔執行失敗問題,最後發現是由於nodejs專案本身有用nssm包成服務,在服務環境的nodejs呼叫的執行檔也執行在服務中,造成程式不會跳出視窗而導致失敗。
準備專案 這邊首先準備一個新的專案,可以參考react官網,完成後參考README.md輸入npm run dev就可以啟動並在瀏覽器看到畫面 準備nssm工具 在google上搜nssm,第一個項目點進去後,找到並下載穩定版,附上下載鏈接 壓縮檔下載完畢後,解壓縮到喜歡的地方,然後進入資料
如果有個算法是2秒以上很耗時的長任務,希望在執行長任務前後修改state渲染loading畫面,可能會難以達到預期效果,會看到loading畫面一閃而過。 把setState改非同步的方法...
4/5React await setStat