What is the method for resetting the counter back to 1 whenever the labels are updated?

I am currently working on a breathing exercise code that involves counting in the following manner:

8-second inhale 
8 second "hold inhale"
12-second "exhale"
8-second "hold exhale" 

Everything is functioning correctly except for the counter, which continues to increment without resetting back to 1. Ideally, it should count from 1 to 8, then reset to 1 and count to 8 again, followed by 1 to 12, and so forth.

// Function to initiate the timer
function startTimer() {
  var timer = document.getElementById('timer');
  var label = document.getElementById('label');
  var count = 1;

  // Timer interval function
  var interval = setInterval(function() {
    // Updating the timer display and label
    timer.textContent = count;
    
    if (count <= 8) {
      label.textContent = 'Inhale';
    } else if (count <= 16) {
      label.textContent = 'Pause Inhale';
    } else if (count <= 28) {
      label.textContent = 'Exhale';
    } else if (count <= 36) {
      label.textContent = 'Pause Exhale';
    }

    // Increase the count
    count++;
    
    // Stopping the timer after reaching the pattern of 8, 8, 12, 8
    if (count === 45) {
      clearInterval(interval);
      startTimer();
    }
  }, 1000); // 1000 milliseconds = 1 second
}

// Initializing the timer
startTimer();
body {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  margin: 0;
  font-family: Arial, sans-serif;
  text-align: center;
}

h1 {
  font-size: 24px;
  font-weight: bold;
}

p {
  font-size: 18px;
}
<h1>Special Timer</h1>
<p id="timer"></p>
<p id="label"></p>

Answer №1

It is important to utilize distinct variables for tracking the count of the current action and the length of the entire cycle.

// Function to initiate the timer
function beginTimer() {
  var timer = document.getElementById('timer');
  var label = document.getElementById('label');
  label.textContent = 'Inhale';
  var actionCount = 1;
  var cycleLength = segcount;

  // Set interval for the timer
  var interval = setInterval(function() {
    // Update the timer display and label
    timer.textContent = cycleLength;

    if (actionCount == 8) {
      label.textContent = 'Pause Inhale';
      cycleLength = 0;
    } else if (actionCount == 16) {
      label.textContent = 'Exhale';
      cycleLength = 0;
    } else if (actionCount == 28) {
      label.textContent = 'Pause Exhale';
      cycleLength = 0;
    }

    // Increment both counts
    actionCount++;
    cycleLength++;

    // Stop the timer after following the 8, 8, 12, 8 pattern
    if (actionCount === 45) {
      clearInterval(interval);
      beginTimer();
    }
  }, 1000); // 1000 milliseconds = 1 second
}

// Initially start the timer
beginTimer();
body {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  margin: 0;
  font-family: Arial, sans-serif;
  text-align: center;
}

h1 {
  font-size: 24px;
  font-weight: bold;
}

p {
  font-size: 18px;
}
<h1>Special Timer</h1>
<p id="timer"></p>
<p id="label"></p>

Answer №2

You may want to consider including an additional variable to keep track of each step, as demonstrated below.

// Implementing the timer function
function startTimer() {
  var timer = document.getElementById('timer');
  var label = document.getElementById('label');
  var count = 0;
  // Introducing 'stepCount' variable to monitor each step counter
  var stepCount = 0;

  // Setting up the interval for the timer
  var interval = setInterval(function() {
    // Updating the timer display and label


    if (count === 0) {
      label.textContent = 'Inhale';
    } else if (count === 8) {
      // resetting stepCount to 0
      stepCount = 0;
      label.textContent = 'Pause Inhale';
    } else if (count === 16) {
      // resetting stepCount to 0
      stepCount = 0;
      label.textContent = 'Exhale';
    } else if (count === 28) {
      // resetting stepCount to 0
      stepCount = 0;
      label.textContent = 'Pause Exhale';
    }
    
    // Increasing count by 1
    count++;
    // Incrementing stepCount
    stepCount++;
    // Displaying the step counter
    timer.textContent = stepCount;

    // Stopping the timer when reaching the 8, 8, 12, 8 pattern
    if (count === 36) {
      clearInterval(interval);
      startTimer();
    }
  }, 1000); // 1000 milliseconds = 1 second
}

// Launching the timer initially
startTimer();
body {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  margin: 0;
  font-family: Arial, sans-serif;
  text-align: center;
}

h1 {
  font-size: 24px;
  font-weight: bold;
}

p {
  font-size: 18px;
}
<h1>Special Timer</h1>
<p id="timer"></p>
<p id="label"></p>

Answer №3

If you're looking for a solution, consider implementing a finite-state machine concept to manage the timer functionality:

// Function for initializing and controlling the timer
function controlTimer() {

  const timerElement = document.getElementById('timer');
  const labelElement = document.getElementById('label');
  let count = 1;
  
  const states = Object.entries({
    'Inhale': 8, 
    'Pause Inhale': 8, 
    'Exhale': 12, 
    'Pause Exhale': 8
  }).map(([label, duration]) => ({label, duration}));
  let state = 0;
 
  const syncUI = () => {
    labelElement.textContent = states[state].label;
    timerElement.textContent = count;
  };
  
  syncUI();
  
   // Set interval for updating the timer display
  return interval = setInterval(function() {

    // Increment count
    count++;

    // Update the timer display and label
    timerElement.textContent = count;

    if (count > states[state].duration) {
      state++;
      if(state === states.length){
        state = 0;
      }
      count = 1;
      syncUI();
    }

  }, 1000); // 1000 milliseconds = 1 second
}

// Initialize and start the timer mechanism
controlTimer();
body {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  margin: 0;
  font-family: Arial, sans-serif;
  text-align: center;
}

h1 {
  font-size: 24px;
  font-weight: bold;
}

p {
  font-size: 18px;
}
<h1>Special Timer</h1>
<p id="timer"></p>
<p id="label"></p>

Answer №4

Your code is currently executing exactly as you have instructed it to do, without any instruction to reset the displayed count. One suggestion for achieving this functionality is by introducing a separate variable called "displayedCount" that resets once the hidden count reaches specific values. Here's an example implementation:

// Initialize timer function
function startTimer() {
  var timer = document.getElementById('timer');
  var label = document.getElementById('label');
  var count = 1;
  var displayedCount = 1;

  // Timer interval setting
  var interval = setInterval(function() {
    // Update timer display and label
    timer.textContent = displayedCount;

    if (count <= 8) {
      label.textContent = 'Inhale';
    } else if (count <= 16) {
      label.textContent = 'Pause Inhale';
    } else if (count <= 28) {
      label.textContent = 'Exhale';
    } else if (count <= 36) {
      label.textContent = 'Pause Exhale';
    }

    // Increment count
    count++;
    if (count === 9 || count === 17 || count === 29 || count === 37) {
      displayedCount = 1;
    } else {
      displayedCount++;
    }

    // Stop timer at specific count
    if (count === 45) {
      clearInterval(interval);
      startTimer();
    }
  }, 1000); // Interval of 1 second
}

// Start the timer initially
startTimer();

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

The request to upload an image to Cloudinary using AngularJS is being blocked due to the origin http://localhost.com:8000 not being allowed by Access-Control-Allow-Origin

I've been attempting to upload images to Cloudinary through my Angular controller without using any libraries. The POST requests are unsigned, and interestingly, I was successful when I tested it with jQuery on a static HTML page. Here is the code sn ...

I need to implement a div-based dropdown with a scrollbar in JavaScript and CSS to prevent it from extending beyond the screen. Additionally, the use of struts is essential in this implementation

Dealing with a dynamically populated div-based dropdown can be tricky, especially when it extends beyond the screen's limits and hides entries. This is an inherited application that lacks support, leaving me to handle it without the necessary expertis ...

Rearrange two HTML tags that are separated by certain fixed tags

I currently have a Div tag with 3 Elements (HTML Tags) inside. The first tag is: field set, The second tag is: div with a fixed position and multiple inner tags, The third tag is: field set. After performing certain conditions in the document ready eve ...

Unable to navigate to a page following selection of a radio button

I have set up HTML code for two radio button options. When the user selects an option and clicks submit, it is supposed to redirect them to the corresponding page. <script src="js/jump.js"></script> <form onsubmit="jump()"> <input ty ...

Use the no-repeat feature to set the background image in an Asp:Chart

I have been working with the asp:Chart control and have found that its BackImage property functions well. However, I have encountered two issues while trying to set the background image. I am unable to successfully set the no-repeat property of the Bac ...

Stop the div from expanding because of oversize text in Bootstrap

I have the following HTML source code for a Bootstrap card: <div class="card shadow-none card-fluid mb-3 mb-md-5"> <div class="row"> <div class="col-md-3 col-lg-3 mb-3 mb-sm-0"> <img class="img-fluid rounded" ...

How to showcase content on bootstrap across varying screen dimensions

When designing my website, I envisioned having three different options presented upon entering the site. Depending on the size of the screen, I wanted to display varying content. For XL screens, I wanted all content to be visible, similar to the picture. ...

Error alert: Unable to find the specified word

Having trouble writing a word to the database due to an error: ReferenceError: Patikrinta is not defined. Below is my ajax script for sending data to a PHP file, and then the PHP script itself if needed. Haven't found a solution on Stack Overflow. $s ...

Stable Banner with Automatic Scroll to Sections

I have implemented a script that allows for smooth scrolling to different sections within a webpage when clicking on links in the top navigation menu. In the HTML, I've assigned IDs to each section (section1, section2, section3, etc.) and linked these ...

Properly maintaining child processes created with child_process.spawn() in node.js

Check out this example code: #!/usr/bin/env node "use strict"; var child_process = require('child_process'); var x = child_process.spawn('sleep', [100],); throw new Error("failure"); This code spawns a child process and immediately ...

Customizing translations for various domains in Vue-i18n

Our app has a global reach and our company is undergoing a rebranding process in certain markets. For instance, we are currently known as "Acme Company" in the U.S. and Canada, but now we aim to be recognized as "Acme Company" in the U.S. and "Foo Company ...

Examining the false positive detection of an apparent visibility issue with

My goal is to check if the document is NOT scrollable using this code snippet: $el = document.documentElement const noscroll = $el.clientHeight === $el.scrollHeight // false console.log($el.clientHeight) // 977 console.log($el.scrollHeight) // 991 consol ...

Monitoring a specific property within an array of objects with AngularJS

I am facing an issue with the data in my controller $scope.data = { home: { baseValue: "1", name: "home" }, contact: { baseValue: "2", name: "contract" } // numerous ...

What could be causing my Vuex store state to consistently come up empty in middleware when accessing it through SSR (Server-Side Rendering) with NuxtJS?

Question: I am facing an issue with my middleware files. More specifically, I have a file named authenticated.js. In this file, I have a function that checks for authentication. Here is the code snippet: export default function (context) { //console.l ...

What is the optimal order for executing JavaScript, jQuery, CSS, and other controls to render an HTML page efficiently?

What are some recommended strategies for optimizing webpage loading speed? What key factors should be taken into consideration? ...

Importing pixi-sound in the right way for PIXI JS

I have a question regarding the proper way to import pixi-sound into my project. I am facing an issue with the following code snippet: import * as PIXI from "pixi.js"; import PIXI_SOUND from "pixi-sound"; const EFFECT_SOUNDS = [...list of music] for (le ...

How to extract value from the URL in NextJS

I am attempting to pass a value through the URL and then extract that value in search.js using a router. However, I keep encountering this error: TypeError: Cannot read properties of undefined (reading 'q') <form onSubmit={handleSubmit}&g ...

Navigating through IE z-index complications to position a modal *above* a YUI Panel

Within my web application, I have implemented an informational pop-up modal using a <div> element with the CSS attribute "display" set to "none". To display this modal when needed, a JavaScript code snippet is used to toggle the display attribute. W ...

Why won't my Chrome content script load even though I have the correct syntax and have tried troubleshooting?

I'm facing an issue with my extension where the file content.js is not being loaded on any webpage despite trying multiple troubleshooting steps. I've tried different permissions, changing site patterns, reinstalling, restarting Chrome, adjusting ...

The touch events are not detected on Pixi.js when buttons are placed on a stage that has been both scaled and

Currently, I am developing a game using pixi js. In order to ensure that the game appears consistent on all screens, I have implemented the following scaling logic: this.scale = Math.max(this.viewWidth, this.viewHeight) / (2048 * this.ratio); Additionall ...