Experiencing a problem with a loop structure in my code

I've been trying to create a loop that will increase the temperature by 10 degrees every 2 minutes. However, I'm struggling to figure out how to stop the temperature at 120 degrees after 16 minutes. Any suggestions on how to solve this issue?

var temp = 30,
    min = 0;
console.log("Cooking started at " + temp + " deg");

for (min = 0; min <= 25; min++) {

   if (min % 2 === 0) {
       temp += 10;
       console.log("Minutes passed: " + min + 
                    ", we are cooking at " + temp + " deg");
   }

   if (min % 2 !== 0 && min === 25) {
       console.log("Total minutes of cooking is 25 min");
   }
}

The expected output should be as follows:

Cooking started at 30 deg
Minutes passed: 0, we are cooking at 40 deg
Minutes passed: 2, we are cooking at 50 deg
Minutes passed: 4, we are cooking at 60 deg
Minutes passed: 6, we are cooking at 70 deg
Minutes passed: 8, we are cooking at 80 deg
Minutes passed: 10, we are cooking at 90 deg
Minutes passed: 12, we are cooking at 100 deg
Minutes passed: 14, we are cooking at 110 deg
Minutes passed: 16, we are cooking at 120 deg
Minutes passed: 18, we are cooking at 120 deg
Minutes passed: 20, we are cooking at 120 deg
Minutes passed: 22, we are cooking at 120 deg
Minutes passed: 24, we are cooking at 120 deg
Total minutes of cooking is 25 min

Answer №1

To simplify the code, you can use a formula for temp in relation to min. By utilizing Math.min, you can ensure that the temperature doesn't go beyond a certain value. Since you only need to display something every two minutes, consider adjusting your loop accordingly. Additionally, since the 25-minute message is only displayed once at the end, it can be placed outside of the loop:

console.log("Cooking started at 30 deg");
for (var min = 0; min <= 25; min+=2) {
   var temp = Math.min(120, 40 + min*5);
   console.log("Minutes passed: " + min + ", we are cooking at " + temp + " deg");
}
console.log("Total minutes of cooking is 25 min");

Answer №2

It's curious that you would continue looping even after reaching the maximum value you know. One simple solution is to limit the loop count to <=16 since you are aware that the process should end there.

var temp = 30,
    min = 0;
    console.log("Cooking started at " + temp + " deg");

for (min = 0; min <= 16; min++) {

   if (min % 2 === 0) {
       temp += 10;
       console.log("Minutes passed: " + min + 
                    ", we are cooking at " + temp + " deg");
   }

   if (min % 2 !== 0 && min === 16) {
       console.log("Total minutes of cooking is 25 min");
   }
}

Alternatively, if you must reach 25 minutes, you can add a condition for 16 minutes and adjust the temperature temp accordingly:

var temp = 30,
    min = 0;
    console.log("Cooking started at " + temp + " deg");

for (min = 0; min <= 25; min++) {

   if(min >= 16) {
      // If we've reached this point, at least 16 minutes of cooking have passed
      temp = 120;  // Set temp to maximum
      console.log("Minutes passed: " + min + ", we are cooking at " + temp + " deg");
   } else if (min % 2 === 0) {
       // If we've arrived here, it means we're less than 16 minutes in and on an even minute, so proceed as usual
       temp += 10;
       console.log("Minutes passed: " + min + ", we are cooking at " + temp + " deg");
   }

   if (min % 2 !== 0 && min === 25) {
       console.log("Total minutes of cooking is 25 min");
   }
}

Answer №3

To ensure optimal cooking, implement a condition that checks if the elapsed time exceeds 16 minutes and then adjusts the temperature to 120 degrees. If not, increase the temperature by 5 degrees:

var temp = 30,
min = 0;
console.log("Initiating cooking at " + temp + " degrees");

for (min = 0; min <= 25; min++) {

   if (min >= 16) {
       temp = 120;
   } else {
       temp += 5;
   }

   if (min % 2 === 0) {
       console.log("Minutes passed: " + min + 
                    ", current temperature: " + temp + " degrees");
   }

   if (min % 2 !== 0 && min === 25) {
       console.log("Total cook time: 25 minutes");
   }
}

It's advisable to segregate tasks like logging and temperature adjustments into distinct code blocks for clarity.

Answer №4

It seems like you're looking to halt the modifications on temp once it hits 120. You can achieve this using either the break; or continue; statements.

The break; statement will completely terminate the for loop, ending the iteration when it's called.

On the other hand, the continue; statement will simply bypass the remaining code within that specific iteration of the loop. If you wish to continue with the rest of the loop even after reaching 120, then this is the suitable choice. Here's an example:

var temp = 30,
min = 0;
console.log("Cooking started at " + temp + " degrees");

for (min = 0; min <= 25; min++) {

  if(temp >= 120) {
    continue;
    // or 'break;' if you want to exit the entire loop.
  }

  if (min % 2 === 0) {
      temp += 10;
      console.log("Minutes passed: " + min + 
                ", cooking temperature: " + temp + " degrees");
  }

  if (min % 2 !== 0 && min === 25) {
      console.log("Total cooking time is 25 minutes");
  }
}

This code snippet hasn't been thoroughly tested, but it demonstrates the concept.

Answer №5

After verifying the value of the variable temp, you can use the break statement to exit the loop.

console.clear();
var temp = 30,
  min = 0;
console.log("Cooking started at " + temp + " deg");

for (min = 0; min <= 25; min++) {
  if (temp >= 120) {
    break;
  }

  if (min % 2 === 0) {
    temp += 10;
    console.log("Minutes passed: " + min +
      ", we are cooking at " + temp + " deg");
  }

  if (min % 2 !== 0 && min === 25) {
    console.log("Total minutes of cooking is 25 min");
  }
}

Answer №6

If you want to condense your code, try using a ternary operator inside the console.log():

var temperature = 30,
    minutes = 0;
    console.log("Cooking started at " + temperature + " deg");

for (minutes = 0; minutes <= 25; minutes++) {
   if (minutes % 2 === 0) {
       temperature += 10;
       console.log("Minutes passed: " + minutes + 
                    ", we are cooking at " + (temperature>120?120:temperature) + " deg");
   }

   if (minutes % 2 !== 0 && minutes === 25) {
       console.log("Total minutes of cooking is 25 min");
   }
}

Here's what the shorthand notation means:

(temperature>120?120:temperature)
// equivalent to
if (temperature>120) { 120 } else { temperature }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am in the process of creating a dropdown menu for a navbar that will appear when the cursor hovers over a specific element, complete with an arrow pointing upwards

In my current project with NextJS and Tailwind CSS, I've successfully created a dropdown menu but I'm facing an issue with positioning the arrow to point to the specific element being hovered on. In a previous version, I tried rotating a div at 4 ...

Mastering Node.js: Writing to a Write Stream on the 'finish' Event

I'm currently using Node.js streams to process a text file line by line, apply some transformations, and then generate an SVG file based on the data. However, I am facing an issue where when I try to write the closing tag (</svg>) after all pro ...

Exploring NodeJS Express Routing Across Various URIs/URLs

In my application, there is a public folder that contains HTML/CSS3/JS code. This folder has two main parts: one with the public facing index.html inside public/web and another with an admin view exclusively for admins. Below is the basic layout: public ...

Understanding the scope of jQuery variables within a function

myClass.prototype.toggle = function() { var elements = []; $.getJSON('http://localhost/jsoner.php', function(data) { $.each(data, function(index, value) { elements.push(value); alert(elements[0]); //this is functioning } ...

Leveraging jQuery selectors to manipulate data received from an Ajax response

I am encountering an issue with an Ajax call and response. Previously, I had a block of regular javascript code that successfully transformed my select element into a select2 widget. However, when I attempt to convert the select element into a select2 usi ...

ng-if directive does not show data in AngularJS

I have a dynamic collection of images and videos that I want to display one at a time. Specifically, when I click on an image ID, I want it to show the corresponding image, and when I click on a video ID, I want it to show the relevant video. Below is the ...

Maintain the expanded sub-menu when the mouse leaves the area, but a sub-option has been

Implementing a side menu with parent and child options that dynamically display content in the main div on the right when a child option is selected. The parent options are initially shown upon page load, and the child options appear when the mouse hovers ...

The contrast between FormData and jQuery's serialize() method: Exploring the distinctions

Recently I came across a situation where I needed to submit a form using AJAX. While researching the most efficient method, I discovered two popular approaches - some developers were utilizing jQuery#serialize() while others were opting for FormData. Here ...

Issue: Adjustment of elements' size using an "onclick" method when reaching specific screen width

Seeking assistance with implementing media queries in JavaScript. Can an object be resized from JavaScript code based on a specific screen width, rather than the default one? For example, if I have a button that opens a div with a height of 600px when cli ...

What is the reason for Cloud Firestore's realtime database fetching all items?

Currently, I am developing a project with vuejs and I am facing an issue where I need to fetch only the last created item from Firestore's realtime database. However, when I execute the following code snippet, it retrieves all items from the database ...

Tips for adjusting the height of both an iframe and a div to fit perfectly at 100% combined

Struggling to make an iframe and div both have 100% full height on the page? I need a footer menu with 280px height, leaving the rest of the page for the iframe. After extensive research, it seems like jQuery might be necessary as CSS Flex didn't wor ...

When refreshing the page, the authentication token set in the Vuex store using axios in Nuxt.js/Vue.js gets reset

Here is the code snippet I am using to manage login, logout, user retrieval, and token setting for all axios requests as an auth header. While this code works perfectly during client-side rendering - such as logging in, storing the token in cookies, etc. ...

Divs expanding below content in IE on a particular server

Currently, I am facing an issue with a JavaScript div that expands correctly over other content in most situations but goes under the content in one specific scenario. I am unsure about where to begin debugging this problem. To provide some context, the d ...

Show the "Splash" picture, then switch to a newly uploaded image and show it for a set amount of time

I am in the process of developing an HTML/JavaScript page that will showcase a splash image (splash.jpg) until it gets replaced by another image file called latest.jpg. Once this latest.jpg is displayed, I want it to remain on the screen for 90 seconds bef ...

Dealing with asynchronous tasks in JavaScript

I am currently delving into the world of Node development and struggling to grasp the asynchronous nature of JavaScript and Node.js. My project involves creating a microservices backend web server using Express in the gateway service, which then translates ...

Tips for creating a seamless merge from background color to a pristine white hue

Seeking a seamless transition from the background color to white at the top and bottom of the box, similar to the example screenshot. Current look: The top and bottom of the box are filled with the background color until the edge https://i.stack.imgur.com ...

Enable the click functionality for a disabled MI TextField

I'm utilizing a disabled TextField in my project and updating it using React Hooks useState to modify the value property of the TextField. const [employee , setEmployee] = React.useState('') <TextField fullWidth ...

I am seeking a way to conceal text in an HTML document using JavaScript when the browser window width is less than a specified amount, and reveal it when the window width exceeds that value

I attempted to use the window.screen.width method, but it appears that the script only runs once (upon page load). I am seeking a way for the code to run continuously. Below is my JavaScript snippet: var textinSelected = document.getElementById("se ...

generate a collection using a string of variables

I'm looking for a way to pass a string as the name of an array to a function, and have that function create the array. For example: createArray('array_name', data); function createArray(array_name, data){ var new_array = []; // pe ...

Utilizing Ajax for Efficiently Updating a Singular Field within a Designated Object

How can I use Ajax to Update a Single Field in a Specific Object? I have a table in my postgres database with numerous records. I am interested in using a jquery Ajax request to update just one field in a particular object within that table. Is it possibl ...