I'm attempting to showcase a counter on the screen by utilizing innerHTML, but despite implementing a sleep function within a loop, it doesn't seem to be functioning as intended

Is there a way to create a timer that counts down from a specific range to zero instead of displaying 0:00 immediately without any changes using innerHTML? I tried using the sleep function, but it just keeps the screen the same until it displays zero. How can I make it look like an actual countdown? Please help!


function sleep(t){
   let timeStart = new Date().getTime();
     while(true)
      {
       let elapsedTime = new Date().getTime() - timeStart;
       if(elapsedTime > t){
       break;
      }
    }
}

function startLoop(){

  let minutesValue = document.getElementById("minutes-input").value;
  let secondsValue = document.getElementById("seconds-input").value;
  let minutesDisplay = document.getElementById("minutes");
  let secondsDisplay = document.getElementById("seconds");

for(var i=0;i < minutesValue; i++)
{
  minutesDisplay.innerHTML=i;
  console.log(i);
  for (var j =1; j<=59; j++) {
     sleep(1000);
    secondsDisplay.innerHTML=j;
    console.log(j);
  }
}

Answer №1

Let's see if this explanation helps. I'm aware that CSS is typically placed in an external file, but for the sake of convenience, here it is integrated within the HTML...

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

<input type="text" id="minutes-input" value="1">
<input type="text" id="seconds-input" value="10">
<div style="border: 2px solid black; width: 100px; height: 15px;" id="minutes"></div>
<div style="border: 2px solid black; width: 100px; height: 15px;" id="seconds"></div>
<button type="button" onclick="setInterval(updateTime, 1000);">Start counting</button>

<script>
let minutesValue = document.getElementById("minutes-input").value;
let secondsValue = document.getElementById("seconds-input").value;
let minutesElement = document.getElementById("minutes");
let secondsElement = document.getElementById("seconds");

minutesElement.innerHTML = minutesValue;   // starting time in minutes
secondsElement.innerHTML = secondsValue;   // starting time in seconds

function updateTime() {
    minutesElement.innerHTML = minutesValue;
    if(secondsValue > 0) {
        secondsElement.innerHTML = --secondsValue;
        if(minutesValue === 0 && secondsValue === 0) {
            return;                    // stop counting
        }
        if(secondsValue === 0) {
            secondsValue = 60;
            minutesValue--;
        }
    }  
}
</script>
</body>
</html>

If there are any clarifications needed, feel free to inquire...

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

Enhancing parent component props in React-router-dom: A guide to updating them

Here is the structure of my App component: const App = (props) => ( <BrowserRouter> <PageTheme {...some props I'd like to change on route change}> <Switch> <Route exact path="/example"> <E ...

Encountering unfamiliar characters in Mac OS while converting language in VueJs

When using the get text plugin for language translation in VueJs, everything works perfectly on all browsers in linux-ubuntu OS. However, upon opening it in any browser on MacOS, I am encountering unknown symbols as shown below in the screenshots. Image o ...

Vue.js has a feature where it automatically closes the form tag within a for loop

In my Vue.js application, I have created a table where each row is a form with a submit button. This is the code snippet I am using: <div id="admin-user"> <table class="table"> <tr v-for="(user, index) in users"> < ...

Tips for managing encoding when transmitting values through ajax

When working in WordPress, I encountered an issue with an Ajax call where a value was being sent inaccurately. blow = \'blo\ Upon receiving the value on the server end, it appeared to have an extra backslash (\). blow = \\& ...

Using Nextjs Image as the Background for Layout

I have a question regarding implementing a common background image for all pages in my app. Currently, I have the main page.js code that displays an image as the background using Next Image component. However, I would like this background to be present thr ...

I need to mass upload a collection of resumes stored in a zip file, then extract and display the content of each resume using a combination of HTML

I recently used a service to extract and retrieve the contents of a zip file. I am trying to read the content of the files and integrate them into the scope of my Angular project. Any suggestions would be greatly appreciated. Below is an outline of my func ...

"Running experiments with Google Ads and Google Analytics scripts results in a blank page being displayed

Currently, I am working on a plain HTML file and conducting tests to ensure that the Google Ads and Analytics scripts are functioning correctly before implementing them on other pages. A colleague who has an AdSense account provided me with the script code ...

Encountering difficulties when attempting to run initial React Native app

Struggling with my journey of learning react-native, I encountered a roadblock while trying to run the application. Here is the error log. I'm hopeful for some assistance from anyone who can lend a hand. The development server returned response erro ...

Is it possible to utilize two nested routes in React Router Dom v6 while using the colon symbol ( : )?

I launched a new react website called My Website Take a look at my website for better understanding In the blog section, I implemented two nested routes <Route path="/blog" element={<Blog />} > <Route path="" e ...

Enabling JavaScript functions to accept a variable number of arguments

I am looking to enhance the versatility of the function below by enabling it to accept multiple callbacks to other functions if they are specified in the arguments. $(function() { function icisDashBox(colorElem, thisWidth, thisHeight, completeCallBack ...

Strip the date after converting from milliseconds to a date

When my server back end sends the time value as milliseconds (1479515722195), I use a library function to convert it to a date format like Sat Nov 19 2016 11:35:22. Now, I need to figure out how to separate the date and time components. I only require th ...

Transferring SignalR element across various HTML pages

When working with SignalR in JavaScript, I have encountered an issue with two objects: a Connection object and a Hub Proxy object. var connection = $.hubConnection(); connection.url = 'http://localhost:xxx/signalr'; var contosoChatHubProxy = ...

Is there a problem with how the public directory is currently configured?

Recently, I completed a Webpack project and organized it in the following structure: static/ // Contains js and css files index.html // Main file I decided to integrate this setup into an Express environment by placing it inside the public/ folder. Here& ...

Capture the user's input data and use it to populate the value of a select option

I'm facing an issue with a dropdown list that has different values. My goal is to display a hidden div with the id "othertype" whenever I select the "Other" option and then type in an input field to save that data. However, this functionality is not w ...

Using Javascript to enable drag and drop functionality

After attempting to use a guide for creating drag and drop features, I encountered an issue. I followed the steps outlined at Despite the detailed instructions in the guide, I cannot seem to get the functionality to work. Is there a mistake in my code? I ...

Verifying the frequency of two specific strings within a JavaScript string

How can I determine the number of times two distinct patterns occur in a given string? Specifically, I need to identify instances of fly or flies. While I have managed to find occurrences of one pattern, I'm unsure how to search for both. Here's ...

Utilize the .not() filter function in JavaScript

I am trying to apply a filter of not(.pseudo-element) using JavaScript, but I am unsure how to add it. So far, I have been able to extract #app from the DOM with the following code: const app = document.getElementById('app') app.style.filter ...

Implement a feature that allows a user to upload multiple files from a Uint8ClampedArray using

After creating a binary file in the Browser using JavaScript as Uint8ClampedArray, I am now faced with the task of uploading it to a webserver as if it was selected from a file-picker. My attempt at this resulted in the following code: var data = new Uint ...

if XHR function fails, then resort to alternate method

I am currently working on an XMLHttpRequest and I have a specific requirement. If the XHR fails, I would like to perform another action (such as reading a local file), but I want to execute this outside of the XHR function itself. In addition, my project ...

Cannot retrieve top 2 values from an object - Angular 6 bug fixing issue

I've been attempting to identify the top 2 values in an object within an array, but I'm encountering issues. Previously, I successfully achieved this with average values that were not within an array, however, when looping through some results an ...