Utilizing a function within a loop that is nested within another loop

//Exercise 3a:
for (var a=1; a<12; a++) {
    for (var b=00; b<60; b++) {
        for (var c=00; c<60; c++) {
            console.log(a + ':' + b + ':' + c + 'AM');
        }
    }
}
for (var alpha=12; alpha<13; alpha++) {
    for (var x=00; x<60; x++) {
        for (var y=00; y<60; y++) {
            console.log(alpha + ':' + x + ':' + y + 'PM');
        }
    }
}
for (var d=1; d<13; d++) {
    for (var e=00; e<60; e++) {
        for (var f=00; f<60; f++) {
            console.log(d + ':' + e + ':' + f + 'PM');
        }
    }
}

//Exercise 3b:
function toTwoDigits(number) {
    if (number < 10 && number >= 0) {
        return '0' + number;
    } else 
        return number;
    }

//Applying to Exercise 3a:
for (var q=0; q<10; q++) {
    toTwoDigits(q);   
}

I am starting my journey into Javascript and have crafted a for loop that generates the seconds in each minute for every hour in a day, on a 12-hour clock. The second part of the exercise required me to create a function that converts any single-digit number to a two-digit number. I believe I have completed both tasks successfully, but I am struggling with implementing the function into the for loop. Can anyone provide some assistance with this, please?

for loop and function

Answer №1

To implement a time interval in your code, you can use the following snippet:

setInterval(function(){ alert("Hello"); }, 1000);

The value 1000 in the code represents 1000 milliseconds, which is equivalent to 1 second.

You have the flexibility to replace the anonymous function with your own named function

<script>setInterval(function(){ console.log(new Date().toLocaleTimeString());+"\n"; }, 1000);</script>

Answer №2

To implement the oneToTwo function, simply include it in the loop:

for (var x = 1; x < 12; x++) {
  for (var y = 00; y < 60; y++) {
    for (var z = 00; z < 60; z++) {
      console.log(oneToTwo(x) + ':' + oneToTwo(y) + ':' + oneToTwo(z) + 'AM');
    }
  }
}

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

JavaScript functioning in Firefox but not Chrome

Here is the code snippet in question: $('#ad img').each(function(){ if($(this).width() > 125){ $(this).height('auto'); $(this).width(125); } }); While this code works correctly in Firefox, it seems to have i ...

Are there any restrictions on using class functions to access dynamically allocated arrays in C++?

I have started working on a program for a class that involves reading a file containing a series of floating-point numbers. I am confident that using Doubles will not be an issue. I am assuming that by calling my function using array1.readDataFromFile();, ...

How to customize the background of radio buttons in HTML

I want the background color to stay consistent as lightgray for each <ul>. Currently, clicking the radio button causes the ul's background to change incorrectly. I am unsure of how to loop through all available ul elements using jQuery and woul ...

Arranging a list based on the child property in a React component

Within my application, I have an array mapped to a map that generates a div with a data-date attribute as shown below: It's worth noting that the array cannot be sorted here since there are no dates available for comparison, only the element ID cons ...

Is it possible to run an existing NextJS app with API routes on a mobile platform using either Capacitor or Expo?

I have an established NextJS application that heavily relies on Next's API routes. My goal is to transition the current codebase to function in a mobile environment. I've experimented with Capacitor and attempted to export it as a static site, bu ...

Modifying the input field's name attribute while utilizing multiple datasets in typeahead.js

I am currently utilizing typeahead.js with multiple datasets, following the guidance provided here. I have chosen not to employ Bloodhound in my implementation, resulting in some differences in my code structure, outlined below: $('#search .typeahead ...

Having trouble retrieving the elements from the JSON array defined in EJS within the JavaScript script tags

<div> let arrayData='<%= myJsonArray %>' <!--myJsonArray is passed to this ejs file via the render function in index.js when rendering this ejs file --> </div> <script> let index=0; function getData(){ c ...

Utilizing dispatch sequentially within ngrx StateManagement

I have been working on a project that utilizes ngrx for state management. Although I am still fairly new to ngrx, I understand the basics such as using this.store.select to subscribe to any state changes. However, I have a question regarding the following ...

Change the z-index of divs when clicked

When a button is clicked, I want to iterate through a group of absolutely positioned children divs with varying z-indexes. The goal is for the z-index of the currently visible div to decrease on each click, creating a looping effect where only one div is v ...

Material-UI React is unable to identify the `underlineStyle` property on a specific HTML element

I tried implementing a custom style to change the underline color of a material-UI TextField element, following an example I found. http://www.material-ui.com/#/components/text-field Unfortunately, when I attempt to add my own styling, React does not rec ...

NextAuth.js in conjunction with nextjs version 13 presents a unique challenge involving a custom login page redirection loop when using Middleware - specifically a

I am encountering an issue with NextAuth.js in Nextjs version 13 while utilizing a custom login page. Each time I attempt to access /auth/signin, it first redirects to /login, and then loops back to /auth/signin, resulting in a redirection loop. This probl ...

Linking a button to a (click) event within HTML content fetched from the backend

Hey there, I'm facing a scenario where I have an angular service that sends a HTTP request to the backend for some HTML code. Once the HTML is received, I'm inserting it into the component's HTML using <div [innerHTML]="..."/>. The iss ...

What is the method for extracting latitude and longitude values individually from JSON data?

Upon receiving the JSON response from the Google Maps API stored in a variable named 'obj', I noticed that alerting obj.name returns "Pancakes on the Rocks". To access the icon, I can use obj.icon. However, I am struggling to retrieve separate va ...

How can you access the URL of a resource action in Angular?

In my Angular application, I have created a resource named 'Files' with the following definition: app.factory('Files', function($resource) { return $resource('/api/accounts/:account_id/sites/:site_id/files/:file_id'); }); ...

Issue: The variable '$viewMap[...]' is either null or undefined

Unfortunately, my knowledge of jQuery/Javascript is quite limited. I am encountering a Javascript error when trying to change the "how did you hear about us" dropdown on a form. The error message states: Error: '$viewMap[...]' is null or not an ...

Is there a way to showcase the outcome of a Python script on an HTML webpage?

Hey there, I'm a beginner to coding and I've been working on a little project to track the price of gold in a web application using Flask and Python. In my HTML code, I have a button that, when clicked, takes users to a new route where the gold ...

Creating dynamic web pages using Smarty templating engine to render HTML

I'm attempting to display my unprocessed HTML content using Smarty. {if !empty($brand.description)} {$brand.description} {/if} Although the initial text includes spaces and line breaks, when viewed, the HTML appears as plain text. I also experimen ...

Determine the absence of values in a randomly generated array and identify the quantity of missing values

My current challenge involves solving CodeSignal projects, and I recently encountered a problem where a random array of numbers is given, requiring me to determine how many additional numbers are needed to make the array consecutive. For instance, if the ...

Just a Quick Query About Regular Expressions

I need help removing a specific part from a URL string, which looks like this: http://.....?page=1. I am aware that the code "document.URL.replace("?page=[0-9]", "")" does not work, so I am curious to learn how to accomplish this task correctly. Thank you ...

The browser has surpassed the maximum call stack size while trying to refresh with socket.io, causing an error

I've encountered an issue with my Node js server crashing whenever I refresh the browser. The websocket connection works fine initially, but upon refreshing, the server crashes with the following error: E:\Back\node_modules\socket.io-pa ...