Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

128
Views
How can I create a task function can delay and output in different order in JavaScript

Define a task function and the output after execution is as follows

task('james') 
// james starts work
task('james').waitFirst(5).do('push') 
// wait 5s, james do push, james starts work
task('james').wait(5).do('commit') 
// james starts work, wait 5s, james do commit

I have no idea how to create such a wait function, does anyone can help me about that or give me some ideas.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Here is my solution with a little annoying .end() call after every task() call.

function task(name) {
  const register = {};

  const preventCallAfter = (methodName) => {
    if (methodName in register)
      throw new Error(`You cannot use "wait" and "waitFirst" together.`);
  };

  return {
    wait(seconds) {
      preventCallAfter("waitFirst");
      register.wait = seconds;
      return this;
    },
    waitFirst(seconds) {
      preventCallAfter("wait");
      register.waitFirst = seconds;
      return this;
    },
    do(workName) {
      if ("workName" in register)
        throw new Error(`The .do() method is already called.`);

      register.workName = workName;
      return this;
    },
    end() {
      if ("wait" in register) {
        console.log(`${name} starts work.`);
        console.log(`wait ${register.wait} seconds.`);
        setTimeout(
          () => console.log(`${name} do ${register.workName}`),
          register.wait * 1000
        );
      } else if ("waitFirst" in register) {
        console.log(`wait ${register.waitFirst} seconds.`);

        setTimeout(() => {
          console.log(`${name} do ${register.workName}`);
          console.log(`${name} starts work.`);
        }, register.waitFirst * 1000);
      } else console.log(`${name} starts work.`);
    },
  };
}

// task("james").end();
// james starts work
// task("james").waitFirst(5).do("push").end();
// wait 5s, chenlee do push, james starts work
task("james").wait(5).do("commit").end();
// james starts work, wait 5s, james do commit

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!