Setting The Cooking Time With Date

📝 We continue in the Speedy Chef project folder throughout this section.

Updating our pizza object with the date

In the addToOven function, earlier we added a placeholder date:

function addToOven() {
  pizzasCompleteForOrder++;
  const pizzaName = document.querySelector('#current_pizza').innerText;
  if (pizzaName) {
    const pizzaForOven = {
      name: pizzaName,
      timeAdded: '5/5/28',
    };
    oven.push(pizzaForOven);
    displayOvenItems();
  }
}

This can be updated to now use the current date dynamically:

timeAdded: Date.now(),

Remember, Date.now() will be in milliseconds, so we can remove this from the oven after a certain time. But first, we need to set the cooking time we want to use.

Set cooking time

Add the following alongside the rest of our variables:

const cookingTime = 20;
let completedPizzas = 0;

We can also add a new function. This function will loop over all the pizzas in the oven, once every second. It will then remove any which have been in for our set cookingTime of 20 seconds:

function checkOven() {
  // 1. check once per second
  setInterval(function() {
    // 2. loop over all items in our oven array
    oven.forEach(function(pizza) {

    });
  }, 1000);
};

Checking if pizzas are cooked

Inside the loop, an if statement can be used to check the time difference:

oven.forEach(function(pizza) {
  if (Date.now() - cookingTime * 1000 > pizza.timeAdded) {
    oven.shift(); // remove first item (array method)
    displayOvenItems(); // reset oven contents after removing pizza
  }
});

Here we are checking if the current date, minus the cooking time, is greater than the time the pizza was added to the oven.

We can also keep track of the number of pizzas we have cooked by increasing the variable we just created:

if (Date.now() - cookingTime * 1000 > pizza.timeAdded) {
    oven.shift();
    displayOvenItems();
    completedPizzas++; // if pizza is cooked, increase our variable
  }

This will be used later when we add the stats section. The last thing is to call this checkOven function when we begin the game:

function startOfGame() {
  // ...
  checkOven();
}

Test this out and the pizzas should only show in the oven for the set 20 seconds. You have now reached the end of this section!

fireworks image

Completed code after this lesson

If needed, here is the completed code we added to the starter file (index.js):

let oven = [];
const ovenCapacity = 6;
let pizzasCompleteForOrder = 0;
let gameStarted = false;
const gameLength = 300;
let countdownTime = gameLength;
const cookingTime = 20;
let completedPizzas = 0;
document.querySelector(
    "#gameLength"
).innerText = `Game length is ${gameLength} seconds`;
document.querySelector("#endBtn").style.display = "none";

function buildElement(elementName, elementContent) {
    const element = document.createElement(elementName);
    const content = document.createTextNode(elementContent);
    element.appendChild(content);
    return element;
}

function createListOfPizzas(pizzas) {
    const pizzaList = document.createElement("ul");
    pizzas.forEach(function (pizza) {
        const orderQuantityEl = buildElement("span", `${pizza.quantity} - `);
        const pizzaNameElement = buildElement("span", pizza.name);
        pizzaNameElement.classList.add("pizza_name");
        const pizzaItem = document.createElement("li");
        pizzaItem.append(orderQuantityEl, pizzaNameElement);
        pizzaList.appendChild(pizzaItem);
    });
    return pizzaList;
}

function createSingleOrder(order) {
    const orderWrapper = document.createElement("div");
    orderWrapper.className = "order_wrapper";
    orderWrapper.addEventListener("click", selectCurrentOrder);
    const orderNumberEl = buildElement("h4", `Order: ${order.id}`);
    orderWrapper.appendChild(orderNumberEl);
    const pizzaList = createListOfPizzas(order.pizzas);
    orderWrapper.appendChild(pizzaList);
    return orderWrapper;
}

function createOrdersList() {
    document.querySelector("#orders").innerHTML = "";
    orders.forEach(function (order) {
        const singleOrder = createSingleOrder(order);
        document.querySelector("#orders").appendChild(singleOrder);
    });
}

function selectCurrentOrder(e) {
    const pizzas = document.querySelectorAll(".pizza_name");
    pizzas.forEach(function (pizza) {
        pizza.addEventListener("click", setCurrentPizza);
    });

    if (document.querySelector("#working_on").children.length > 1) {
        return;
    }
    let element = e.target;
    const orderWrapper = element.closest(".order_wrapper");
    if (orderWrapper !== null) {
        orderWrapper.removeEventListener("click", selectCurrentOrder);
        const orderDiv = document.querySelector("#working_on");
        orderDiv.appendChild(orderWrapper);
    }
}

function setCurrentPizza(e) {
    const pizzaName = e.target.innerText;
    document.querySelector("#current_pizza").innerText = pizzaName;
    displayMethod(pizzaName);
}

function displayMethod(pizzaName) {
    document.querySelector("#pizza_name").innerText = pizzaName;
    const selectedPizza = pizzas.find((pizza) => pizza.name === pizzaName);
    const methodSteps = selectedPizza.method.split(".");
    document.querySelector("#pizza_method").innerHTML = "";
    methodSteps.forEach(function (method) {
        const element = buildElement("li", method);
        document.querySelector("#pizza_method").appendChild(element);
    });
}

function addToOven() {
    pizzasCompleteForOrder++;
    const pizzaName = document.querySelector("#current_pizza").innerText;
    if (pizzaName) {
        const pizzaForOven = {
            name: pizzaName,
            timeAdded: Date.now(),
        };
        oven.push(pizzaForOven);
        displayOvenItems();
    }
}

document.querySelector("#addToOven").addEventListener("click", addToOven);

function displayOvenItems() {
    document.querySelector("#oven").innerHTML = "";
    oven.forEach(function (pizza) {
        const pizzaDiv = document.createElement("div");
        pizzaDiv.className = "pizza_div";
        const image = document.createElement("img");
        image.src = "pizza.svg";
        const pizzaName = buildElement("p", `(${pizza.name})`);
        pizzaDiv.append(image, pizzaName);
        document.querySelector("#oven").appendChild(pizzaDiv);
    });
}

function startOfGame() {
    if (gameStarted) {
        return;
    }
    document.querySelector("#startBtn").style.display = "none";
    document.querySelector("#endBtn").style.display = "inline";

    gameStarted = true;
    const orders = document.getElementsByClassName("order_wrapper");
    Array.from(orders).forEach(function (order) {
        order.remove();
    });
    createOrdersList();
    ordersTimer();
    countdownTimerRef = setInterval(countdownTimer, 1000);
    gameTimer();

    document.querySelector("#message").innerText =
        "Chef, our first orders are coming in!!!";
    setTimeout(function () {
        document.querySelector("#message").innerText = "";
    }, 3000);
    checkOven();
}

function endOfGame() {
    gameStarted = false;
    clearInterval(orderTimerRef);
    clearInterval(countdownTimerRef);
    clearTimeout(gameTimerRef);
    document.querySelector("#endBtn").style.display = "none";
    document.querySelector("#startBtn").style.display = "inline";
}
document.querySelector("#startBtn").addEventListener("click", startOfGame);
document.querySelector("#endBtn").addEventListener("click", endOfGame);

let orderNumber = orders.length + 1;

function generateNewOrder() {
    let pizzas = [];
    const orderItem = Math.ceil(Math.random() * 5);
    for (i = 1; i <= orderItem; i++) {
        pizzas.push(generateNewPizza());
    }
    const newOrder = {
        id: orderNumber,
        pizzas,
    };
    orders.push(newOrder);
    orderNumber++;

    createOrdersList();
}

function generateNewPizza() {
    const quantity = Math.ceil(Math.random() * 3);
    const randomPizza = pizzas[Math.floor(Math.random() * pizzas.length)];
    const pizza = {
        quantity,
        name: randomPizza.name,
    };
    return pizza;
}
generateNewPizza();

let orderTimerRef = "";
function ordersTimer() {
    orderTimerRef = setInterval(generateNewOrder, 3000);
}

let countdownTimerRef = "";
function countdownTimer() {
    // reduce variable value
    countdownTime -= 1;
    // update the DOM
    document.querySelector(
        "#gameLength"
    ).innerText = `Time left: ${countdownTime}`;
}

let gameTimerRef = "";
function gameTimer() {
    gameTimerRef = setTimeout(endOfGame, gameLength * 1000);
}

function checkOven() {
    setInterval(function () {
        oven.forEach(function (pizza) {
            if (Date.now() - cookingTime * 1000 > pizza.timeAdded) {
                oven.shift();
                displayOvenItems();
                completedPizzas++;
            }
        });
    }, 1000);
}