標籤:
我們知道,在適用js的時候,程式是單線程執行的,而且如果遇到阻塞就會將瀏覽器卡死。
能否非同步執行,讓程式不再卡呢?
可以,用setTimeout。
但是,問題又來了,如果我有這樣的要求:
執行一個函數a;
暫停5秒;
執行函數b;
暫停5秒;
輸出結果,暫停5秒後自動清空顯示。
以上的這段邏輯虛擬碼使用JavaScript難以直接實現,因為setTimeout的時候,你根本不知道他什麼時候執行結束。
jQuery有when方法可以解決問題,但是其嵌套性又讓人傷神。
為此,我造了一個簡單的輪子,發布出來,與開源社區共用。
輪子代碼:
/** * * @authors sunsoft ([email protected]) * @date 2015-04-30 22:26:22 * @version v1.0 */function Executor() { return { oSequence: [], Params: {}, microInterval: 10, add: function(func, delay) { var that = this; var option = { delayInit: delay, startDateTime: null, state: "wait", delegateFunc: func, done: function() { this.state = "done"; }, getParam: function(paramname) { return that.Params[paramname]; }, setParam: function(paramname, value) { that.Params[paramname] = value; } }; this.oSequence.push(option); }, exec: function() { this.oSequence.reverse(); var that = this; //active the first one this.oSequence[that.oSequence.length - 1].startDateTime = new Date(); var fTmp = function() { if (that.oSequence.length > 0) { var oTask = that.oSequence[that.oSequence.length - 1]; if (oTask.state == "done") { //如果任務已經完成,就刪除這個節點 that.oSequence.pop(); //如果還有下一個節點,則將它的開始時間設定好 if (that.oSequence.length > 0) { oTask = that.oSequence[that.oSequence.length - 1]; oTask.startDateTime = new Date(); } } if (oTask.state == "wait" && oTask.startDateTime != null && (new Date()) - oTask.startDateTime > oTask.delayInit) { oTask.state = "processing"; oTask.delegateFunc(oTask); } setTimeout(fTmp, that.microInterval); } else { console.log("done"); } } fTmp(); }, sleep: function(millSec) { this.add(function(task) { task.done(); }, millSec); } };}
測試代碼:
$(document).ready(function() { examples();});function examples() { var oExecutor = new Executor(); oExecutor.microInterval = 1; oExecutor.add(function(task) { //alert("we are the world"); console.log((new Date()).toLocaleString()) task.setParam("love","MJ"); task.done(); }, 0); oExecutor.sleep(2000); oExecutor.add(function(task) { console.log((new Date()).toLocaleString()) //alert("我又來了"); console.log(task.getParam("love")); task.done(); }, 0); oExecutor.exec();}
[JavaScript]順序的非同步執行