Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

130
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda