Javascript Egg Timer

I am currently in the process of developing a unique egg timer application that allows users to input values through various form select tags. However, I have encountered a NaN error when trying to set the timer with the JavaScript code provided below. Here is a section of the HTML and the JavaScript code I am working on:

<html>
<head>
<script language = "javascript" type = "text/javascript">

var minutes

var miuntes=setInterval(timer, 1000); //1000 will run it every 1 second

function timer(m)
{
  minutes = m;
  minutes=minutes-1;
  if (minutes <= 0)
  {
     clearInterval(minutes);
     //timer ended, do something here
     return;
  }

 document.getElementById("txt").innerHTML=minutes + "minutes"; 
}

function checktimer()
{

var checkbox1 = form.preference.value;
var checkbox2 = form.eggsize.value;
var checkbox3 = form.suacepansize.value;

if(checkbox1 == 1 && checkbox2 == 1 && checkbox3 == 1)
{
m = 3;
s = 0;
}

timer(m);
}

</script>

</head>
<body>
<div id = "txt"> </div>

    <form id="form" onclick ="checktimer()">

    <div class = "question">
    <div class="circle"> <h2 class = "whiteh2"> 1 </h2></div>
    <div class="question-text"><h6>How do you like your egg? </h6> </div>
    <select id="prefernce" name ="preference">
  <option value="1">Soft</option>
  <option value="2">Medium</option>
  <option value="3">Hard</option>
</select>

    </div> 

<div class = "question">
    <div class="circle"> <h2 class = "whiteh2"> 2 </h2></div>
    <div class="question-text"><h6>What size is your egg? </h6> </div>
    <select id="eggsize" name = "eggsize">
  <option value="1">Small</option>
  <option value="2">Medium</option>
  <option value="3">Large</option>
</select>

    </div>

    <div class = "question">
    <div class="circle"> <h2 class = "whiteh2"> 3 </h2></div>
    <div class="question-text"><h6>What size is the saucepan? </h6> </div>
    <select id="saucepansize" name = "suacepansize">
  <option value="1">Small</option>
  <option value="2">Medium</option>
  <option value="3">Large</option>
</select>

    </div>

        <div class = "question">
            <input type="submit" id="button" name="submit" value = "Go" onclick="checktimer()"/> <br/> 
        </div>

    </form>

    </div>

</body>
</html>

Answer №1

Here are the alterations I've made:

  1. I adjusted the event from onclick to onsubmit, and now the function returns false to prevent the form from submitting.
  2. The interval initiates when the page loads, which causes it to clear instantly - so I began the interval from the onsubmit handler.
  3. To avoid confusion with two variables named "minutes," one of which was incorrectly spelled, I gave the interval variable a new name.
  4. The argument m is no longer necessary since you have a global minutes variable.

Note: Currently, the countdown ticks down at a rate of one minute per second - for a slower pace, consider multiplying the minutes by 60 and counting in seconds or firing the interval once per minute.

Below is the revised script:

<html>
<head>
<script type="text/javascript">
var minutes = 0;
var interval;

function timer() {
  minutes = minutes - 1;

  document.getElementById("txt").innerHTML= minutes + " minutes"; // check spelling

  if (minutes <= 0) {
     //counter ended, do something here
     window.clearInterval(interval);
     return;
  }
}

function checktimer() {
    var checkbox1 = form.preference.value;
    var checkbox2 = form.eggsize.value;
    var checkbox3 = form.suacepansize.value;

    if(checkbox1 == 1 && checkbox2 == 1 && checkbox3 == 1) {
        minutes = 3;
        s = 0;
    }

    interval = setInterval(timer, 1000);

    return false;
}
</script>
</head>
<body>
<div id = "txt"> </div>

    <form id="form" onsubmit="return checktimer()">

    <div class = "question">
    <div class="circle"> <h2 class = "whiteh2"> 1 </h2></div>
    <div class="question-text"><h6>How do you like your egg? </h6> </div>
    <select id="prefernce" name ="preference">
  <option value="1">Soft</option>
  <option value="2">Medium</option>
  <option value="3">Hard</option>
</select>
    </div> <!--Ends the question div-->

...
(Note: The rest of the HTML code remains unchanged)

Answer №2

let minutes = setInterval(timer, 1000);

The issue in your code is that you haven't passed any arguments to the function timer, causing the variable m to be undefined. When undefined is used in arithmetic operations with numbers, it results in NaN, which explains the problem you are facing. To pass an argument to your function, you need to wrap the timer call in a function expression:

let minutes = setInterval(function() {
    timer( ... );
}, 1000);

Replace ... with the desired number input for the function timer.

Additionally, there is a typo in the variable declaration where you spelled minutes incorrectly. Lastly, make sure to include the closing </script> tag.

Answer №3

edit

var miuntes=setInterval(timer, 1000);

changing it to

var minutes=setInterval(timer, 1000);

and give it a shot

Answer №4

Counting down to ensure all answers are complete

function initiateTimer(minutes, elementID, onFinish) {
    var countDown = minutes * 60 * 1000;
    var time = new Date(0, 0, 0, 0, 0, 0);
    time.setTime(countDown);

    function count(t) {
        if (countDown > 0) {
            countDown -= 1000;
            time.setTime(countDown);
            document.getElementById(elementID).innerHTML = (time.getHours() - 1) + ":" + time.getMinutes() + ":" + time.getSeconds();
        } else {
            clearInterval(interval);
            onFinish();
        }
    }

    var interval = setInterval(count, 1000);
}

initiateTimer(1, "Time", function () { 
    alert("Timer Completed");
});

Check out this JSBin example

In summary:

<head>
    <script language="javascript" type="text/javascript">
        function startTimer(minutes, elementID, onFinish) {
            var countDown = minutes * 60 * 1000;
            var time = new Date(0, 0, 0, 0, 0, 0);
            time.setTime(countDown);

            function count(t) {
                if (countDown > 0) {
                    countDown -= 1000;
                    time.setTime(countDown);
                    document.getElementById(elementID).innerHTML = (time.getHours() - 1) + ":" + time.getMinutes() + ":" + time.getSeconds();
                } else {
                    clearInterval(inter);
                    onFinish();
                }
            }

            var inter = setInterval(count, 1000);
        }

        function validateTimer() {

            var checkbox1 = form.select1.value;
            var checkbox2 = form.select2.value;
            var checkbox3 = form.select3.value;

            if (checkbox1 == 1 && checkbox2 == 1 && checkbox3 == 1) {
                minutes = 3;
              seconds = 0;
            }

            startTimer(minutes, "txt", function () {
                alert("Egg is ready")
            });

        }
    </script>
</head>

<body>
    <div id="txt"></div>
    <form id="form" onclick="validateTimer()">
        <div class="question">
            <select id="select1" name="select1">
                <option value="1">Soft</option>
                <option value="2">Medium</option>
                <option value="3">Hard</option>
            </select>
        </div>
        
        <div class="question">
            <select id="select2" name="select2">
                <option value="1">Small</option>
                <option value="2">Medium</option>
                <option value="3">Large</option>
            </select>
        </div>
        
        <div class="question">
            <select id="select3" name="select3">
                <option value="1">Small</option>
                <option value="2">Medium</option>
                <option value="3">Large</option>
            </select>
        </div>
        
        <div class="question">
            <input type="button" id="button" name="submit" value="Go" onclick="validateTimer()"
            />
            <br/>
        </div>
    </form>
    </div>
</body>

Here's another JSBin demo

You can adjust the timer format and egg readiness times as needed

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

Can you show me the steps for linking the next method of an EventEmitter?

After emitting an event, I am looking to run some additional code. Is there a method to chain the .next() function in this way? @Output() myEvent = new EventEmitter<string>(); this.myEvent.next({‘test string’}).onComplete(console.log('done& ...

react-webcam npm package for optimizing video size

In my React app, I'm utilizing the npm package react-webcam. The <Webcam /> component is enclosed within a div with a dimension of {width: 100vw, height 100vh} I aim for the video element to adjust to the parent div's size and cover 100% ...

The back button on an Angular JS application should display a confirmation dialog when pressed

I am currently working on an AngularJS mobile app that consists of various modules. One of my requirements is to access the device's back button within the application, and I also need a dialog with "OK" and "Cancel" options. Clicking on "OK" should ...

"Encountering issue with the find() function following a successful outcome

I am encountering some issues with my extension. In the following code snippet, I am using a find() function to extract data from an external page: $.ajax({ url: 'http://www.subspedia.tv/traduzioni.php', success: function(data) { ...

Adjusting the timing of a scheduled meeting

Is there a way for me to update the time of a Subject within my service? I'm considering abstracting this function into a service: date: Date; setTime(hours: number, mins: number, secs: number): void { this.date.setHours(hours); this.date.s ...

Data binding in one direction with 2 input fields

In the registration form, there are fields for firstname, lastname, and displayname. When the firstname is updated, I want that change to be reflected in the displayname field if it's currently empty. I've set the update to happen on blur, and a ...

Getting the full referrer URL can be achieved by using various methods depending

I am currently working with ASP.Net. My goal is to retrieve the complete referrer URL when visitors arrive at my website from: https://www.google.co.il/webhp?sourceid=chrome-instant&rlz=1C1CHEU_iwIL457IL457&ion=1&espv=2&ie=UTF-8#q=%D7%90 ...

Merging asynchronous requests to create a unified GET endpoint

In my current project, I am attempting to make calls to a GET API with three different configurations for the region parameter. My goal is to combine the results into a single result object and have the API return it as JSON format. My approach involves u ...

Displaying altered textContent

I am working with an SVG stored as a string and making some adjustments to it. The final result is being displayed as text within targetDiv. <html lang="en"> <head> <title>Output Modified</title> </head> <body> ...

ESLint encountered an error while attempting to load the configuration "next/babel" for extension

Every time I try to generate a build of my Next.js app by running "npm run build," I keep encountering this error. Check out the error I'm getting while running npm run build here. Also, take a look at my .eslintrc.json file here and my .babelrc file ...

Issues encountered when trying to execute npm start: "The function this.htmlWebpackPlugin.getHooks is not recognized."

My background in web development is weak, and I'm facing a challenging situation. I had to take over the work of a colleague who left, and now I'm trying to finish the site we were working on. Since then, I've been learning about web develop ...

Caution: React detecting an active event listener on a scrolling-dependent 'touchstart' action

I am facing an issue with a React component that contains a Material-UI Slider. Whenever this component renders, I receive the following warning message: "Added non-passive event listener to a scroll-blocking 'touchstart' event. Consider marking ...

React is up and running smoothly on my local machine, but unfortunately encountering issues on Vercel

I have encountered an issue while trying to deploy my website on Vercel. Despite the build logs showing a successful compilation, I am receiving a "failed to compile" error: [16:43:24.951] Running build in Washington, D.C., USA (East) – iad1 [16:43:25.05 ...

Utilize jQuery to extract URL parameters and incorporate them into a script

I have a unique link: http://mywebsite.org/product/page?var_one=result1&var_two=result2&var_three=result3&var_four=result4 The values can vary, meaning the parameters are not fixed. My example includes 4 parameters, but there could be more ...

replace the tsconfig.json file with the one provided in the package

While working on my React app and installing a third-party package using TypeScript, I encountered an error message that said: Class constructor Name cannot be invoked without 'new' I attempted to declare a variable with 'new', but tha ...

Equalize the color of overlapping background events with non-overlapping background events in fullcalendar

events:[ {overlap:false, display:'background', start:'2021-12-23 10:15:00', end:'2021-12-23 10:30:00'}, {overlap:false, display:'background', start:'2021-12-23 10:30:00', end:'2021-12-23 10:45:00&a ...

Error encountered while attempting to import a virtual module, import resolution unsuccessful

I've been working on creating type declarations for a Javascript module in Typescript. My goal is to define interfaces using what I believe is a virtual module. Initially, I had no trouble defining the base module types. However, when attempting to im ...

Having trouble with a malfunctioning part of the API in my NodeJS code. Any suggestions on how to resolve the issue

I'm currently working on developing a REST API in NodeJS for an online store. Here's a snippet of my code for handling POST requests: router.post('/', (req, res, next) => { const order = new Order({ _id: new mongoose.Typ ...

Clicking on the button will reset the counter

I have a code snippet that counts down from 15 and displays "times over" after 15 seconds have passed. The issue arises when a user clicks the button multiple times, resulting in multiple countdowns appearing in the same Div. I am looking for a way to rese ...

Receiving an undefined value when trying to access the index of a data list array

I'm currently working on implementing a datalist that gets populated from a JavaScript array and want to identify which part of the array was clicked on. After some debugging, I discovered that my arrays are returning undefined or 0. I've trans ...