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

Exploring the depths of JavaScript JSON elements

After processing my PHP code, it generates a JSON output that contains multiple entries in the same structure. Here is an example with two entries: { "0": { "campaign_id": "31", "title": "new title", "description": "new descrip ...

How can the value of a number in Angular be changed without altering its original value?

Imagine having the initial number 100. If I enter 50 in another input, it should add 50 to 100. However, if I then change the value from 50 to 80, the total should be 180 and not 230. The goal is always to add numbers to the original sum, not the new valu ...

Unable to pass the jQuery value - troubleshooting tips for Laravel

JavaScript Issue return response()->json([ 'category' => $category, 'editRoute' => $artistCategoriesEditRoute ]); AJAX Response category Object { id: 1, title: "tt", parent_id: 0, … } id ...

Performing an Ajax post request to a PHP script in order to retrieve a PHP variable using XMLHttpRequest

I am looking to dynamically update my table using JavaScript every few seconds. Currently, I have set up an AJAX post request to my update.php file and trigger it if it is set. Then, I execute a MySQL query to retrieve the data and store the resultset in ...

Having trouble sending a request in next.js with Docker during the build process?

When utilizing the getStaticProps function to send a request to my backend API from another Docker container, I am encountering an issue. Despite ensuring that the API URL is accurate, the static page fails to be created. This is due to the requirement for ...

Unique Javascript Library Focused on AJAX

Looking for a specific JavaScript library that focuses solely on AJAX functionality, such as a basic XMLHttp wrapper. ...

Troubleshooting the issue: AngularJS not functioning properly with radio button selection to show specific div containing input field

Looking for some help with radio buttons: I need the selection of radio buttons to display their respective input boxes. I have included a snippet of my HTML and controller code below. In my controller, I am using ng-change to call a function that uses jQu ...

CKEditor seems to have overlooked the importance of proper paragraph formatting

Incorporating CKEditor into my front-end project using Laravel has been a great help. However, I am facing an issue where I want to eliminate automatic paragraphs but still allow users to create them by clicking the paragraph button. Is there a way to ac ...

Creating subpages using IDs can be accomplished by following these simple steps

Currently, I am in the process of developing a website that contains a plethora of information, specifically news articles. Each news article on my site features an introduction and a header. Upon clicking on a particular news article, the full content is ...

Emulate an AngularJS ng-click action

My website has HTML code with three buttons: <button ng-click='showStats(player.data,0)'>Death Match</button> <button ng-click='showStats(player.data,1)'>Champions Rumble</button> <button ng-click='sho ...

What is the best way to save data from a jQuery plugin to a database using ASP .NET MVC?

I have a jQuery plugin called "Slider" that displays the current price of an item. I would like to enhance it by allowing users to change prices using the jQuery slider and update them in the database. Here is the model: public class Item { public in ...

Error: The sort method cannot be applied to oResults as it is not a

I encountered this issue. $.ajax({ url: '${searchPatientFileURL}', data: data, success: function(oResults) { console.log("Results:...->"+oResults); oResults.sort(function ...

access various paths to distinct iframes

<?php // Specify the directory path, can be either absolute or relative $dirPath = "C:/xampp/htdocs/statistics/pdf/"; // Open the specified directory and check if it's opened successfully if ($handle = opendir($dirPath)) { // Keep readin ...

What is the technique used by express.js to handle ReferenceError?

// Here is a sample code snippet app.get("/test", (req, res) => { return res.status(200).send(SOME_UNDEFINED_VAR); }); If a ReferenceError occurs, express.js will automatically send a 500 error response. express.js logs the ReferenceError to std ...

Using Laravel Blade Variables in JavaScript Code

Trying to access a variable within blade syntax has posed a challenge for me: success: function(resp) { console.log(resp) var MsgClass = 'alert-danger'; $("#overlay").hide(); ...

Ways to ensure the title changer works seamlessly for everyone

Having a title changer for elements visible in the viewport is crucial. However, the current setup only works for a single division and fails to function with multiple divisions. Click Here for Live Testing and Viewing Check out the jsFiddle for Code V ...

Encountering the 404 Page Not Found error upon refreshing the page while utilizing parallel routes

I'm currently developing a webapp dashboard using the latest version of Next.js 13 with app router. It features a dashboard and search bar at the top. I attempted to implement parallel routes. The @search folder contains the search bar and page.jsx wh ...

When it comes to using the text() function, the statement encounters difficulty

let person = $(".tekst").text(); if (person=="XxX") { $("#discu").css("display", "none"); } alert(person); When I access my element with class .tekst and get its text using the text() function, it correctly displays as XxX, which is what I expected. ...

Filtering Tables with AngularJS

Currently, I'm experimenting with using angularJS to filter data in a table. My goal is to load the data from a JSON file that has a structure like this (example file): [{name: "Moroni", age: 50}, {name: "Tiancum", age: 43}, { ...

Having trouble with jQuery events not triggering properly after dynamically inserting elements using an ajax request?

It's strange that all my jQuery events become unresponsive after an AJAX call. When I use a load function, once the JSP reloads, none of the events seem to work properly. Any suggestions? Below is the code that triggers the function call: $('#p ...