After the completion of the JavaScript timer, the existing text remains in place even when the new text is displayed

https://jsfiddle.net/zLfuwdtu/1/

I've developed a script that tracks down to date 'Date1'. As it counts down, it shows the message "UNTIL FLOW." Once this timer reaches zero, another timer 'Date2' takes its place and displays "ON FLOW."

The issue at hand is that when 'Date1' finishes counting down, it continues to show the message from 'Date1' (UNTIL FLOW) along with the message from 'Date2' (ON FLOW). I need it not to display the message from 'Date1' while showing the message from 'Date2.'

  function getTimeRemaining(endtime) {
  var t = Date.parse(endtime) - Date.parse(new Date());
  var seconds = Math.floor((t / 1000) % 60);
  var minutes = Math.floor((t / 1000 / 60) % 60);
  var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
  var days = Math.floor(t / (1000 * 60 * 60 * 24));
  return {
    'total': t,
    'days': days,
    'hours': hours,
    'minutes': minutes,
    'seconds': seconds
  };
}

function initializeClock(id, endtime, secondend, newfirstend) {
  var clock = document.getElementById(id);
  var daysSpan = clock.querySelector('.flowDays');
  var hoursSpan = clock.querySelector('.flowHours');
  var minutesSpan = clock.querySelector('.flowMinutes');
  var secondsSpan = clock.querySelector('.flowSeconds');

  function updateClock() {
    var t = getTimeRemaining(endtime);
    if(t.seconds<0)
        {
            clearInterval(timeinterval);
        }
    else
        {
    daysSpan.innerHTML = t.days;
    hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
    minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
    secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);
        }
    if (t.total <= 0) {     
    document.getElementById("flowWindow").textContent= 'ON FLOW! ';
        endtime=secondend;
        }
    else 
    {document.getElementById("flow2Window").textContent= 'UNTIL FLOW';}
  }
  updateClock();
  var timeinterval = setInterval(updateClock, 1000);
}

var firstend = 'Sun Jul 05 2016 03:38:40 GMT-0400 (EDT)';
var secondend = 'Sun Jul 08 2016 20:52:10 GMT-0400 (EDT)';
initializeClock('flowClockdiv', firstend, secondend, firstend);

Answer №1

function getTimeRemaining(endtime) {
    var t = Date.parse(endtime) - Date.parse(new Date());
    var seconds = Math.floor((t / 1000) % 60);
    var minutes = Math.floor((t / 1000 / 60) % 60);
    var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
    var days = Math.floor(t / (1000 * 60 * 60 * 24));
    return {
        'total': t,
        'days': days,
        'hours': hours,
        'minutes': minutes,
        'seconds': seconds
    };
}

function initializeClock(id, flow) {
    var clock = document.getElementById(id);
    var daysSpan = clock.querySelector('.flowDays');
    var hoursSpan = clock.querySelector('.flowHours');
    var minutesSpan = clock.querySelector('.flowMinutes');
    var secondsSpan = clock.querySelector('.flowSeconds');

    function updateBoard(flow) {
        document.getElementById("flowWindow").textContent = '';
        document.getElementById("flow2Window").textContent = '';
        switch(flow[current].name)
        {
            case 'on':
                document.getElementById("flowWindow").textContent = 'ON FLOW! ';
                break;
            case 'until':
                document.getElementById("flow2Window").textContent = 'UNTIL FLOW';
                break;
        }
    }

    function updateClock() {
        var t = getTimeRemaining(flow[current].end);
        if (t.seconds >= 0) {
            daysSpan.innerHTML = t.days;
            hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
            minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
            secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);
        }
        if (t.total <= 0) {
            flow.shift();
            updateBoard(flow);
            if (flow[current].name == 'stop') {
                clearInterval(timer);
            }
        }
    }
    updateBoard(flow);
    var timer = setInterval(updateClock, 1000);
}
var current = 0;
var firstend = new Date();
var secondend = new Date();
firstend.setSeconds(firstend.getSeconds() + 5);
secondend.setSeconds(secondend.getSeconds() + 10);
var flow = [
    { 'name': 'until', 'end': firstend },
    { 'name': 'on', 'end': secondend },
    { 'name': 'stop', 'end': null }
];
initializeClock('flowClockdiv', flow);

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

Sending the "Enter Key" using JavaScript in Selenium can be achieved by utilizing the "executeScript" function

I'm currently developing an automation flow using IE 11 with Selenium and Java. On a particular web page, I need to input a value in a Text Box and then press Enter. I have successfully managed to input the values using the following code: // The &ap ...

I'm having trouble displaying the result of my calculation in the code. Could it be because I forgot to include an output tag?

I am attempting to develop a Miles Per Gallon (MPG) calculator using Javascript. However, I'm encountering difficulties with displaying the results once the "Calculate" button is pressed. <html> <head> <title> MPG Calculator </ti ...

MenuIcon Component is experiencing difficulty being rendered

I am attempting to construct an IconMenu within the AppBar Component. My project is being developed using create-react-app. This is how my code appears: index.js import React from 'react'; import ReactDOM from 'react-dom'; import &a ...

Formik React struggling with error management and handling tasks accurately

I am currently using the Formik template to develop a Login Form. onSubmit={( values, { setSubmitting, setErrors /* setValues and other goodies */ } ) => { props.logMeIn(va ...

When using React hooks forms, setting default values from a reduced array does not automatically populate the form. However, manually entering the same object into the form does

As I work with react hooks forms, I am facing a challenge in setting default values for a form generated by mapping over an array to output the inputs. After reducing the array into an object format like {name0:"fijs",name1:"3838"...}, manually passing thi ...

Utilize Angular's ng-repeat directive to iterate through this JSON data structure for implementing user-to

Struggling with the user-to-user messaging interface on an app and having difficulty using ng-repeat on the items. Here is the provided data: { "ID": 4118, "CreatedDate": "2015-08-20T03:12:50.397", "recipient": [ { ...

Exploring the nuances between Ruby on Rails and the responses from json and JavaScript ajax

I am interested in learning the most effective method for handling an ajax request. Would it be better to send json data and parse it on the client side (for instance using pure), or should I generate javascript at the server side and send back the respo ...

Popup window displaying website content upon DOM loading, ensuring compatibility across various browsers

I am facing a challenge with my HTML popup window where I need to add text after opening the window using a specific function: var win = window.open('private.php', data.sender_id , 'width=300,height=400'); win.win ...

Leveraging client API callback variables within a Node.js backend system

If I send a request on the client side using the code snippet below public/foo.js function bar() { fetch('https://api.github.com/') .then(response => response.json()) .then(data => { console.log(data) }) .catch( ...

How to Capture Clicks on Any DOM Element in React

Currently working on a web project using React and Node. My goal is to monitor all clicks across the entire document and verify if the previous click occurred within a 2-minute timeframe. ...

Does writing JavaScript code that is easier to understand make it run slower?

While browsing the web, I stumbled upon this neat JavaScript program (found on Khan Academy) created by another user: /*vars*/ frameRate(0); var Sz=100; var particles=1000; scale(400/Sz); var points=[[floor(Sz/2),floor(Sz/2),false]]; for(var i=0;i<part ...

Incorporating URL addresses and pagination features using React.Js and Material-UI components

I have a functional component-page on my website, where I display a table that fetches data from an API. To improve user experience, I implemented pagination using the Material-UI library. While the pagination functionality works fine in updating the table ...

Issues with routeparams are preventing ng-repeat from functioning properly, without any response or resolution

For my shoppingCart project, I am working on dynamically bringing data into views. I am using routeParams in template.html but facing an issue. The data is arriving normally as checked via ng-href="#/store/{{something.name}}/{{ child.name }}" but it isn&ap ...

JavaScript - Attempting to Add Objects to Array Unsuccessful

After seeing this question raised multiple times, I am determined to find a solution. In my current project, I am tasked with displaying a list of orders and implementing a filter by date functionality. However, I keep encountering an error when trying to ...

The content is overflowing outside the boundaries of the div, yet there is no

I am currently utilizing jQuery to dynamically load the content of a text file into a div element. However, when the content exceeds the dimensions of the div, no scroll bar is displayed. Here is the HTML structure: <!DOCTYPE html> <html lang=" ...

From HTML to Mat Table: Transforming tables for Angular

I am currently facing a challenge with my HTML table, as it is being populated row by row from local storage using a for loop. I am seeking assistance in converting this into an Angular Material table. Despite trying various suggestions and codes recommend ...

"Code snippets customized for React are not functioning properly in the javascriptreact.json file within Visual Studio Code

I'm looking to incorporate some customized React.js code snippets into my Visual Studio Code setup. I am aware of the two files in VSCode that handle this - javascript.json and javascriptreact.json. Although the snippets work well in javascript.json, ...

Determine the length of a string in JavaScript and PHP taking into account "invisible characters" such as and

I have a textarea where users can input text, and I want to show them how many characters they have left as they type using JavaScript or jQuery: var area = 'textarea#zoomcomment'; var c = $(area).val().length; After that, the text is validated ...

The combination of useEffect and Client component has the power to greatly

As a newcomer to React development, I've encountered a blocking error in my code that isn't being detected by Visual Studio Code. Here's the code snippet for my NavBar component: import React, { useState, useEffect } from "react"; import Ima ...

Filter arrays in Vue.js using checkboxes

I'm currently working with vuejs and I need to implement a filtering feature for my array using checkboxes. I attempted to use v-model to filter the array based on three specific options: "Truck," "Van," or "Tx". However, I haven't been successfu ...