-1

I have tried using setTimeout but I added pizzaTask method, the setTimeout doesn't seem to work. Yes, I do not want any async or promises here.

function preparePizza(n) {
  console.log("Finish preparing pizza " + n);
  console.log("Start baking pizza " + n);
  setTimeout(bakePizza, 10000);
}

function bakePizza() {
  console.log("Finish baking pizza");
}

function makePizza(n) {
  console.log("Start preparing pizza " + n);
  setTimeout(preparePizza(n), 5000);
}

function pizzaTask() {
  for (let x = 1; x <= 10; x++) {
    makePizza(x);
  }

  console.log("Read to take new order ...");
}

pizzaTask();
Heretic Monkey
  • 10,498
  • 6
  • 45
  • 102
Steve
  • 1,485
  • 3
  • 17
  • 45
  • 3
    `setTimeout` takes a function - you pass it the return of a function, which is `undefined`, because you call the function inside the brackets. – ASDFGerte Nov 05 '19 at 14:41
  • You can wrap your `preparePizza` call in an arrow function so that you're still able to pass `n` into `preparePizza` without executing it immediately. `setTimeout(() => { preparePizza(n) }, 5000);` – byxor Nov 05 '19 at 14:44
  • https://stackoverflow.com/questions/20890943/javascript-settimeout-not-working proper dupe, along with the non-descriptive "it's not working!" – ASDFGerte Nov 05 '19 at 14:45

1 Answers1

2

The problem is the way you're calling preparePizza(n), this calls the function which returns undefined. You need to pass a function and call it within this function as preparePizza takes an argument n. Solution below.

  function preparePizza(n) {
    console.log("Finish preparing pizza " + n);
    console.log("Start baking pizza " + n);
    setTimeout(bakePizza, 10000);
  }

  function bakePizza() {
    console.log("Finish baking pizza");
  }

  function makePizza(n) {
    console.log("Start preparing pizza " + n);
    setTimeout(function() {
      preparePizza(n)
    }, 5000);
  }

  function pizzaTask() {
    for (let x = 1; x <= 10; x++) {
      makePizza(x);
    }

    console.log("Read to take new order ...");
   }
  
   pizzaTask();
psilocybin
  • 920
  • 5
  • 22
  • but how to make `console.log("Read to take new order ...");` run after finish making all the pizza? – Steve Nov 05 '19 at 15:45
  • and it starts to prepare all the 10 pizza at the same time. How to make it prepare the pizza only after the current pizza finished bakePizza? – Steve Nov 05 '19 at 15:48
  • 1
    Sounds like what you want is promise chaining: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises#Chaining – psilocybin Nov 05 '19 at 15:51