js写的一个Thread函数(更新:添加自定义异常处理)

做项目的时候感觉使用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等),只能捕获前台发生的异常。

发布了28 篇原创文章 · 获赞 16 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/sunboylife/article/details/103775567