如何在setTimeout中包装和“objectize”函数和时间?

时间:2018-02-23 07:10:55

标签: javascript oop settimeout

例如,如果我需要执行任务s1,s2,s3,它将如下所示:

var s1=function(){
  document.write("[1s task]");
  setTimeout(s2,2000);
}
var s2=function(){
  document.write("[2s task]");
  setTimeout(s3,3000);
}
var s3=function(){
  document.write("[3s task]");
}
setTimeout(s1,1000);

但如果我想将顺序从s1,s2,s3更改为s3,s1,s2,则很难维护。如何包装和'客观化'看起来像这样的任务:

mySetTimeout(new MyTask(s1,1000),new MyTask(s2,1000),new MyTask(s3,1000));

因此很容易将顺序从s1,s2,s3更改为s3,s1,s2:

mySetTimeout(new MyTask(s3,3000),new MyTask(s1,1000),new MyTask(s2,2000));

?如何编写mySetTimeout和MyTask?

3 个答案:

答案 0 :(得分:0)

你不知道你正在寻找的解决方案是承诺。它们是表示异步结果的对象,可以与回调函数链接。



function delay(t) {
    return new Promise(resolve => {
        setTimeout(resolve, t);
    });
}

function s1() {
    console.log("[1s task]");
    return delay(1000);
}
function s2() {
    console.log("[2s task]");
    return delay(2000);
}
function s3() {
    console.log("[3s task]");
    return delay(3000);
}

s1().then(s2).then(s3);




答案 1 :(得分:0)

创建一个计划任务,该任务将不同的任务作为参数(下面的示例)

function scheduleTask()
{
   var args = [...arguments];
   var firstTask = args.slice(0,1)[0];
   args = args.slice(1);
   //console.log(args, firstTask);
   firstTask && setTimeout( function(){ 
        firstTask( function(){
          scheduleTask(...args);
       });
   }, 1000); //timeout is constant
}
scheduleTask(s1, s2, s3);

<强>演示

&#13;
&#13;
function scheduleTask()
{
   var args = [...arguments];
   var firstTask = args.slice(0,1)[0];
   args = args.slice(1);
   //console.log(args, firstTask);
   firstTask && setTimeout( function(){ 
        firstTask( function(){
          scheduleTask(...args);
       });
   }, 1000); //timeout is constant
}
scheduleTask(s1, s2, s3);

function s1( cb )
{
   console.log("s1");
   cb();
}

function s2( cb )
{
   console.log("s2");
   cb();
}

function s3( cb )
{
   console.log("s3");
   cb();
}
&#13;
&#13;
&#13;

或者按照@Thomas的建议,您可以通过

来缩短它
function scheduleTask(firstTask, ...args) 
{
  firstTask && setTimeout(function() {
    firstTask(function() {
      scheduleTask(...args);
    });
  }, 1000); //timeout is constant
}

<强>演示

&#13;
&#13;
function scheduleTask(firstTask, ...args) 
{
  firstTask && setTimeout(function() {
    firstTask(function() {
      scheduleTask(...args);
    });
  }, 1000); //timeout is constant
}
scheduleTask(s1, s2, s3);

function s1(cb) {
  console.log("s1");
  cb();
}

function s2(cb) {
  console.log("s2");
  cb();
}

function s3(cb) {
  console.log("s3");
  cb();
}
&#13;
&#13;
&#13;

答案 2 :(得分:0)

我想@ Bergi的承诺方式很好,但你仍然可以在不使用承诺的情况下对你的工作进行排序。只需按照您喜欢的顺序将作业放入数组中,然后使用递归顺序器。

var seqJobs = ([j,...js]) => j && setTimeout(_ => (j.job(), seqJobs(js)), j.dly),
    jobs    = [{job: _ => console.log("[0s task]"), dly: 500},
               {job: _ => console.log("[1s task]"), dly: 2000},
               {job: _ => console.log("[2s task]"), dly: 3000},
               {job: _ => console.log("[3s task]"), dly: 1000}];

seqJobs(jobs);