Tips for showing the counter value on the screen to initiate a countdown

Currently working on a counter, but encountering some issues. The counter field undergoes increment and decrement (set at 5 minutes by default). Upon pressing the 'start' button, the last digit of the counter should be set as the timer in the output field. Below is my proposed solution:

;(function(){
  var output = document.querySelector('#output'),
    btn = document.querySelector('button'),
    min = 5,
    sec = min * 60,
    timer;

setCount(min);

  function setCount(n){
    var c = document.querySelector('#counter'),
        increment = c.children[1].children[0],
        decrement = c.children[1].children[2],
        num  = c.children[1].children[1];      

    increment.onclick = function(){
      if(n >= 1) {num.textContent = ++n;}
    };  

    decrement.onclick = function(){
      if(n > 1) {num.textContent = --n;}
    };  
    num.textContent = n;
   }

  function setTimer(){

    var currentMin = Math.round((sec - 30) / 60),
        currentSec = sec % 60;

    if(currentMin >= 0 ) {currentMin = '0' + currentMin;}
    if(currentSec <= 9 ) {currentSec = '0' + currentSec;}  
    if(sec !== 0){sec--;}
    timer = setTimeout(setTimer,10);  // 10 is for the speedy
    output.textContent = currentMin + ':' + currentSec;  
  }

  btn.addEventListener('click', setTimer, false);
  })();

Check it out here: JS Bin

Answer №1

Summary:

if(n >= 1) {num.textContent = ++n; sec = n * 60;} // Line 15
...
if(n > 1) {num.textContent = --n; sec = n * 60; } // Line 19

Your timer currently calculates the starting minute value based on seconds which is always set to 5 * 60. To ensure accuracy, update the seconds value each time the + or - buttons are clicked.

(function() {
  var output = document.querySelector('#output');
  var btn = document.querySelector('button');
  var min = 5;
  var sec = min * 60;
  var timer;

  var counter = document.querySelector('#counter ul');
  var increment = counter.children[0];
  var decrement = counter.children[2];
  var number = counter.children[1];
  number.textContent = min;

  increment.onclick = function() {
    min++;
    number.textContent = min;
    sec = min * 60;
  };

  decrement.onclick = function() {
    min--;
    if (min < 1) {
      min = 1;
    }
    sec = min * 60;
    number.textContent = min;
  };

  function setTimer() {
    var currentMin = Math.round((sec - 30) / 60),
      currentSec = sec % 60;

    if (currentMin == 0 && currentSec == 0) {
      output.textContent = '00:00';
      return;
    } else {
      timer = setTimeout(setTimer, 10);
    }

    if (currentMin <= 9) {
      currentMin = '0' + currentMin;
    }
    if (currentSec <= 0) {
      currentSec = '0' + currentSec;
    }
    if (sec !== 0) {
      sec--;
    }
    output.textContent = currentMin + ':' + currentSec;
    console.log('currentMin: ' + currentMin);
  }

  btn.addEventListener('click', setTimer, false);

})();
#wrapper {
  width: 300px;
  border: 1px solid #f00;
  text-align: center;
}
#output {
  height: 40px;
  line-height: 40px;
  border-bottom: 1px solid #f00;
}
h4 {
  margin: 10px 0;
}
ul {
  margin: 0;
  padding: 0;
}
li {
  list-style: none;
  width: 40px;
  height: 40px;
  line-height: 40px;
  display: inline-block;
  border: 1px solid #f00;
}
li:nth-child(odd) {
  cursor: pointer;
}
button {
  padding: 5px 15px;
  margin: 10px 0;
}
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>

<body>
  <div id="wrapper">
    <div id="output"></div>
    <div id="counter">
      <h4>counter</h4>
      <ul>
        <li>+</li>
        <li></li>
        <li>-</li>
      </ul>
    </div>
    <button id="start">start</button>
  </div>
</body>

</html>

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

Encountered an issue while trying to update a ServiceWorker for scope - Received a HTTP error

I encountered a puzzling issue with my Vue PWA app, as our error logs are flooded with instances of a particular user experiencing an error that myself and another person cannot reproduce. Failed to update a ServiceWorker for scope ('https://myapp.com ...

Enhancing dashboard functionality: Managing and updating database table rows

Currently, I am in the process of creating a function that allows me to edit table row values from my plugin's dashboard. The table contains fields such as first name, last name, street, and city. My initial thought was to use a thickbox function for ...

Node-RED experiences crashes while attempting to make HTTP requests to access a web service

I'm currently facing a challenge in creating a node that can make web service calls. The tools I'm using are: Node-RED version: v0.17.5 Node.js version: v8.4.0 An exception is being thrown, and here's the error message: node-red_1 ...

When attempting to print a Rectangle on my webpage using JavaScript and taking user input, I encountered an error stating that 'str' is not defined

I'm trying to implement a feature where clicking on the "try it" button will prompt the user for the number of lines and then print that many lines in the form of a rectangle. However, when I run my code, nothing appears on the DOM and there is an err ...

Why do confirm or alert boxes in Safari on Windows require a double click?

I'm currently working on a simple JavaScript example where I want to display an alert box when an HTML button is clicked in SAFARI. However, I've noticed that it requires a double click to make the alert disappear from the screen. Does anyone ha ...

Alter the hues of the triangles on a threeJS plane

Is there a way to create a multicolor plane by changing the colors of the triangles within a mesh? Can the colors of triangles be adjusted in a PlaneGeometry object? ...

Combining meshes results in a lower frame rate

I have combined approximately 2500 meshes, each with its own color set, but my FPS is lower than if I had not merged them. Based on THIS article, merging is recommended to improve FPS performance. Is there something I am overlooking? var materials = new ...

What is the best way to display an AJAX modal pop-up with jQuery?

After clicking on a button within the repeater, my goal is to show an Ajax modal popup using jQuery. Despite my efforts, I am having trouble getting it to display. Does anyone have any suggestions on how to resolve this issue? ...

The configuration for the 'proxy' is all good and properly set

image description While trying to install the npm package "pdf-node", I encountered an error: Error: ENOTFOUND - getaddrinfo failed for . This seems to be a network connectivity issue. To resolve this error, make sure your network settings are configure ...

I'm having trouble getting the aggregation of a child collection to work properly in MongoDB when attempting to apply the $count

Could someone help me troubleshoot my aggregate query? I'm trying to sum the count values for each beacon, but it keeps returning 0. Please let me know if you spot any mistakes in the query. Sample Data [ { ...

Mongoose Exception: Question does not have a constructor

After coming across numerous questions on stack overflow related to this error without finding a solution that works for me, I've decided to ask my own question. (probably due to my limited understanding of javascript/node/mongoose) The modules I am ...

Issue with hamburger menu or modal not functioning properly in Rails 4 with Bootstrap 4 alpha3 and JS

I am encountering an issue while implementing the hamburger menu feature in rails 4 with bootstrap 4. Although the menu is displayed, the dropdown section is not functioning correctly. Despite referring to other resources, I have been unable to resolve thi ...

What is the best way to preserve text input value when going back a page in PHP?

Is there a way to keep the text box value entered by the user even after navigating away from the page? Below is an example of what I am trying to achieve in my code: **main.php** <html> <head></head> <body> <i ...

Populate data in a third-party iframe using a Chrome Extension

Having trouble with my chrome extension that autofills form inputs because the iframe is loaded from a different source, resulting in Chrome restricting script access to the iframe. There are numerous questions about this on SO already. I recently discove ...

I am searching for a tool in ThreeJS that functions similar to AxisHelper, possibly a Helper class or utility

While working with Three.js, I have come across many helpful Helper classes that greatly simplify displaying and modifying the scene. However, there is one particular tool that I am struggling to find again. It is similar to the AxisHelper, but it includes ...

The div contents are only replaced by Ajax when I interrupt the script with an alert

In my HTML code, there is a div that contains a form with two drop down lists inside. Upon pressing the submit button on the form, a JavaScript function is triggered... function retrieveData(url, targetDiv){ var value1 = (document.getElementById( ...

Extracting information from state and showcasing it in a dynamic layout using antd

When I try to use languages from the state in this line {({languages}, {add, remove}) => ...., I encounter a problem referencing the state. The error message .map is not a function is displayed. Upon clicking Add another languages, more input fields sho ...

Troubleshooting Material UI Widget Components

After working diligently on the autocomplete component, I am pleased with how the feature turned out. However, when this component is rendered as a widget on other pages, I'm encountering some style issues due to global styling overrides or additions ...

Passing Data from Child Components to Parent Components in Vue.js

Looking for assistance with a component I have: <BasicFilter></BasicFilter> It contains a select element: <select @change="$emit('onSortName', $event)"> <option value="asc"> A..Z</option><opti ...

Input field in a tableview

I have a ListView that features a dropdown, 4 textboxes and buttons. My goal is to only show the fourth textbox (enclosed in a span) when the dropdown value in each row of the ListView is set to 2. For instance, if there are 5 records being displayed in t ...