What could be causing this code to keep looping?

This is my submission for a class project. The task given was:

"Create a function that will kickstart the program and name it main(). From the main() function, invoke a function named getValue(). The getValue() function will prompt the user to input a number to be used later. Also from the main() function, call a function called getSquareRoot(). The getSquareRoot() function will calculate the square root of the number obtained from the user in the getValue() function. Ensure that you present the results, including the original number and its square root, in a format that is easy to comprehend.

The bolding is part of the original text.

I have written the code below, and it functions properly, except for the fact that some functions are triggered twice, leading to double output display during the second run where userInput receives a value of 0. I am struggling to identify where this 'loop' is being initiated (I am a beginner). Any assistance would be greatly appreciated; I've been staring at it but unable to pinpoint the issue.

<html lang="en">

<head>
<title>Project 3 Part A</title>

    <meta charset="utf-8">      

    <script>

        function main()
        {

            var msg1="";
            var msg2="";                
            var userInput = "";

            getValue(userInput);
            getSquareRoot(userInput);

        }

        function getValue(userInput)
        {

            var userInput = document.getElementById("userNumber").value;
            return getSquareRoot(userInput);

        }

        function getSquareRoot(userInput)           
        {           

            squareRoot = Math.sqrt(userInput);  
            var msg1 = "Your original number was " + userInput + ".";   
            var msg2 = "The square root of " + userInput + " is " + squareRoot + ".";   
            document.getElementById("original").innerHTML += msg1;
            document.getElementById("results").innerHTML += msg2;

        }




    </script>

</head>

<body>

        <br>

    <input type="button" id="userInputButton" onclick="javascript:main();" value="Square root input value: "/>          

    <input type="text" id="userNumber"> 

    </div>

    <div id="original">

    </div>

    <div id="results">

    </div>                      

</body>

Please feel free to provide your insights on how to resolve the duplication issue.

Answer №1

It is important to ensure that each function has a single purpose for optimal efficiency. In this case, the function 'getSquaredRoot' handles both calculating the square root and displaying the result to the user.

Additionally, as mentioned by Lucky Chingi, the getSquaredRoot function is being called twice.


function main() {
    var userInput = getUserInput();        
    var squareRoot = calculateSquareRoot(userInput);

    var message1 = "Your original number was " + userInput + ".";   
    var message2 = "The square root of " + userInput + " is " + squareRoot + ".";   
    document.getElementById("original").innerHTML += message1;
    document.getElementById("results").innerHTML += message2;

}

function getUserInput() {
    return document.getElementById("userNumber").value;
}

function calculateSquareRoot(userInput) {           
    return Math.sqrt(userInput);  
}

This structure provides clear logical separation of functions.

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

Swap out the image for a div element if the image is not found

Is there a way to accurately display an image if it's available, and use a div as a replacement if the image is not present? // How can I determine `imageExists` without encountering cross-origin issues? (imageExists) ? (<img class="avatar-img" sr ...

Disregard earlier callback outcome if there has been a change in the state since then

I am facing an issue with my page that displays a list of countries retrieved from an external library. When I click on a country, it should show me all the cities in that specific country. Each country object has a provided method to fetch the list of c ...

Use a swipe gesture to move through the slideshow on a touchscreen device

I am currently working on a slideshow that allows users to navigate through images by clicking either the next or previous buttons. When a user clicks on one of these buttons, the next or previous image is loaded into the img src, as shown below. In addit ...

The functionality of the Vue.js single file component is not performing as anticipated

Recently, I've been experimenting with Vue and Vue CLI. I came across this amazing vue-tabs-component that I would like to try out. Here is a snippet of my code from App.vue: <template> <div> <tabs> <tab name="Fir ...

How can I effectively assign model data to a service property in an AngularJS controller?

I have established a service to facilitate the sharing of data/state across multiple controllers. One of the controllers updates certain properties within the service using scope data through a save function. The updated data is then accessed by other cont ...

Generating a dynamic sitemap with Next.js

I have been working on a project where I need to create a sitemap, and I am currently using next-sitemap for generation. However, I've encountered an issue with this method, as well as other solutions I've come across, because the sitemap is only ...

What is the method for incorporating a timeout in a promise?

After exploring various methods for adding timeouts to promises, it appears that most rely on the setTimeout() function. Here is the formal definition: The setTimeout() function executes a specified function or evaluates an expression after a set number of ...

Give properties to a function that is being spread inside an object

While working with React, I am facing a challenge of passing props from the instanced component into the mockFn function. The code example below is extracted and incorporates Material UI, but I am struggling on how to structure it in order to have access t ...

Got a not-a-number (NaN) value for the `children` prop in a

Just starting out with React and working on a type racer app. I've encountered an issue while trying to calculate WPM (Words per minute) - the calculation keeps returning 'NaN'. I've double-checked all the variables and ensured there ar ...

My toggleclass function seems to be malfunctioning

I am encountering a strange issue with my jQuery script. It seems to work initially when I toggle between classes, but then requires an extra click every time I want to repeat the process. The classes switch as expected at first, but subsequent toggles req ...

Having trouble getting Fullcalendar to show up on my cordova app

Currently, I am in the process of building a mobile application using ionic and cordova. My goal is to incorporate a timetable system utilizing Fullcalendar and a PHP page that showcases MySQL data in JSON format. Despite my efforts, I am encountering diff ...

Outer div encapsulating inner div within its boundaries

I am looking for a solution where the inner div stays fully contained within the outer div, without overflowing and overlapping with the padding of the outer div. Here is a code sample that demonstrates the issue .inner { /* Overflow */ overflow-wra ...

Using local storage with github sites can lead to some unexpected and peculiar behavior

Currently, I am working on a simple clicker game using HTML and JavaScript. To store the variables money and taxCollecters, I have implemented local storage. However, I am encountering strange issues when trying to use the save and load buttons on the Gi ...

Next.js is refusing to render an array of HTML elements

Consider this scenario where I have a block of code in TypeScript that attempts to create and display a list of elements. Here is a sample implementation: const MenuList = ():ReactElement => { const router = useRouter(), liElements:any = []; con ...

Implementing a Search Box feature in React-leaflet version 3.1.0

Struggling to incorporate a searchbox feature into my react app. Encountering the error message "Attempted import error: 'MapControl' is not exported from 'react-leaflet'" with the latest version of react-leaflet. import { MapContainer, ...

Encountering a typescript error: Attempting to access [key] in an unsafe manner on an object of

I have recently developed a thorough equality checking function. However, I am encountering an issue with the highlighted lines in my code. Does anyone have any suggestions on how to rectify this problem (or perhaps explain what the error signifies)? Her ...

reveal concealed section and seamlessly glide to specified location inside the secret compartment

I have implemented a feature on my website where hidden divs are revealed one at a time, with the screen scrolling to display each specific div. While this code functions well, I am now looking to enhance it by opening the hidden div and smoothly scrolling ...

Obtain data attributes using JQuery's click event handler

I'm facing an issue with a div structure setup as follows: <div class='bar'> <div class='contents'> <div class='element' data-big='join'>JOIN ME</div> <div class=& ...

Symfony: Enhancing array elements with updated bootstrap progress bar

I'm facing a challenging issue that I need help with. Currently, I have a command set up to send a large number of emails (around 300 or more) every 5 minutes using cron in order to distribute a newsletter. My goal is to keep track of how many emails ...

Arranging images next to each other using CSS and HTML

I've been trying to arrange four images side by side, with two on the top row and two on the bottom. I want to ensure they stay consistent across all browser sizes except for mobile. Here is what I have attempted so far: #imageone{ position: absol ...