做項目的時候感覺使用setTimeout()功突發奇想寫了一個Thread函數,不過這也是一個簡單的函數,之前也寫了Stop,和resume等方法由於設計的時候自己感覺代碼太長設計有點問題就刪掉了,不過後期有時間我還會繼續完善,不喜勿噴。
代碼:
var threadCount=0;
function Runnable(task){
this.run=task;
}
function Thread(runnable){
var sleep=0;
var name="Thread-"+(threadCount++);
var target=runnable;
//私有變量,默認異常處理
var uncaughtExceptionHanlder=function(e){
console.log(e.message);
}
this.getName=function(){
return name;
}
this.setName=function(threadName){
name=threadName;
}
this.start=function(){
setTimeout(this.run,sleep);
}
this.setSleep=function(value){
sleep=value;
}
this.run = function () {
if (target != null) {
try {
target.run();
} catch (e) {
uncaughtExceptionHanlder(e);
}
return;
}
console.log('Exception:{線程名稱:"' + name + '",錯誤定位:"thread.js",錯誤信息:"target對象爲null,沒有可執行的任務."}');
}
this.setUncaughtExceptionHanlder=function(exception){
uncaughtExceptionHanlder=exception;
}
}
//繼承
Thread.prototype=new Runnable();
使用:
var runnable=new Runnable(function(){
alert("我執行了");
})
或者
var runnable=new Runnbel(()=>{
alert("我執行了");
})
var thread=new Thread(runnable);
更新: thread.setUncaughtExceptionHanlder((e)=>{
console.log("自定義異常處理體")
});
thread.setSleep(time)//參數代表多久之後開始執行,由於setTimeout在js中屬於宏任務,宏任務會進行註冊入棧當主任務全部執行完畢纔會執行宏任務。所以這裏的time會和我們預期稍有偏差。
thread.start();就是執行一個宏任務,僞異步
thread.run();當作普通方法執行,同步執行。
提醒:目前自定義異常處理不能捕獲後臺的異常(比如 500,404等),只能捕獲前臺發生的異常。