What is the reason for the countdown number's color remaining the same even after it reaches a specific time threshold?

Creating a simple countdown for sports was my idea, but now I'm stuck on the "changeColor" part that I don't have enough knowledge about.

The countdown is functioning perfectly, but customizing the colors and adding CSS animations seems challenging to me. The issue arises with the last part "changeColor".

For instance, when inputting 60s, it should turn green. If inputted as 29s, it should change to orange. And if entered as 9s, it needs to switch to red.

However, why doesn't it automatically change when going from 30 seconds to 29? It should become orange at that point. The same applies for the transition from 10 to 9 seconds, where it should start blinking and turn red, yet nothing happens.

Below is the script:

var CCOUNT;
$(document).ready(function () {
    $('#btnct').click(function () {
        CCOUNT = $('#seconds').val();
        cdreset();
    });
});
var t, count;

function cddisplay() {
    document.getElementById('timespan').innerHTML = count;

}

function countdown() {
    // starts countdown
    cddisplay();
    changeColor(CCOUNT);
    if (count === 0) {
        // time is up
    } else {
        count--;
        t = setTimeout(countdown, 1000);

    }
}

function cdpause() {
    // pauses countdown
    clearTimeout(t);
}

function cdreset() {
    // resets countdown
    cdpause();
    count = CCOUNT;
    cddisplay();
}

function changeColor() {
if (CCOUNT <= 1000 && CCOUNT > 30) {
document.getElementById('counting1').style.color = "#00CC00";

}

else if (CCOUNT <= 30 && CCOUNT > 10) {
document.getElementById('timespan').style.color = "#F87217";
}

else {
document.getElementById('timespan').style.color = "#ff0000";
document.getElementById('timespan').css = ({"text-decoration": "blink", "-webkit-animation-name": "0.2s", "text-decoration": "blink", "-webkit-animation-iteration-count": "infinite", "-webkit-animation-timing-function": "ease-in-out", "-webkit-animation-direction": "alternate"});
}
}

I've made it live on baswijdenes.com/simple-countdown for you to view.

EDIT: Here's the HTML code:

<center>
<form id="frm">
  <div class="counting">  
    <input type="text" class="input" id="seconds" name="seconds" value="0" size="2" maxlength="4" />    

    </div>
    <input type="button" class="btn blue" id="btnct" value="Input" />

</form>

<div class="counting1" id="counting1">
<span type="text" id="timespan">0</span>
</div>
<BR>
<BR>
<div id="divaroundbuttons">
<input type="button" class="btn green" value="Start" onclick="countdown()">
<input type="button" class="btn orange" value="Stop" onclick="cdpause()">
<input type="button" class="btn red" value="Reset" onclick="cdreset()">
</div>
</center>

Answer №1

During my debugging process, I encountered two variables that caused confusion:

  • CCOUNT
  • count

Upon modifying the function countdown() and introducing a console.log(CCOUNT) to monitor the count, it became evident that CCOUNT was not decreasing as expected. After replacing CCOUNT with count, I observed that while the displayed number changed color, it remained fixed.

As a potential solution, I recommend updating the countdown logic to decrement both CCOUNT and count simultaneously:

function countdown() {
    // initiates countdown
    cddisplay();
    changeColor(CCOUNT);
    if (CCOUNT === 0) {
        // timer is up
    } else {
        CCOUNT--;
        count--;
        t = setTimeout(countdown, 1000);

    }
}

Another issue arises with the changeColor() function, where you mentioned the color should switch at 29 and 9 seconds, not 30 and 10 seconds.

I trust this information will be of assistance.

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

Definition in Typescript: The term "value is" refers to a function that takes in any number of arguments of

export function isFunction(value: any): value is (...args: any[]) => any { return typeof value === 'function'; } What is the reason behind using value is (...args: any[]) => any instead of boolean ? ...

Using Javascript to Implement Pinch Zoom on Android

After searching through the depths of the internet, I have yet to come across a viable solution or answer. The challenge at hand is the need to implement pinch zoom functionality for an element (specifically an image) using JavaScript in a Phonegap environ ...

Stacking SVG elements can lead to distortion effects

Currently experimenting with the innovative SVG stacking method to integrate multiple icons into a single file, reducing the browser's HTTP requests. The details of this technique can be found in depth here. In essence, it involves placing numerous S ...

Load texture using ImageUtils with callback in Canvas Renderer

Currently, I am utilizing three.js revision 53. While attempting to load a texture in Canvas Renderer (specifically on Win7) and incorporating a callback for the onLoad event, the texture fails to display. Surprisingly enough, removing the callback functi ...

Ensure each checkbox within a list is selected

My dilemma involves an assortment of checkboxes enclosed within LIs and SPANs in an unordered list. To simplify the checking process, I attempted using jQuery to automatically check all boxes when a button positioned above the UL is clicked. However, my ...

Tips on invoking a JSP and Servlet from JavaScript by passing in a parameter

Check out the code below for calling JavaScript functions: <td><input type="button" name="edit" value="Edit" onclick="editRecord(<%=rs.getString(1)%>);" ></td> <td><input type="button" name="delete" value="Delete" onclic ...

Fill the rows of the <Table> using HTML code

I am encountering an issue with displaying data in a table on a screen: <table id="TransactionTable" class="table table-responsive table-striped"> <thead> <tr> <th></th> <th>Date</ ...

Are there any available tools for automatically creating CSS classes based on your HTML code?

Out of pure curiosity, I am wondering if there is a program or script that can automatically generate a style sheet (with empty values) based on the structure of your HTML document. Essentially, it would extract the IDs and classes you have set in your H ...

What is the best way to handle a large number of nested AJAX GET requests?

My task involves making numerous AJAX GET requests, which must be nested because each request depends on variables from the response of the previous one. Although I was able to make multiple requests with the example below, it becomes impractical when dea ...

What steps are needed to design a search bar similar to Zomato's?

I am looking to create a search bar that resembles the one on . I have managed to make a floating search box on top of my background image. However, I am unsure how to align various input fields and buttons side by side. Below is the current CSS code I am ...

Error: The parent container element cannot be edited until the child element has been properly closed

I received a Script Error stating that I am unable to modify the parent container element before the child element is closed. In response, I clicked Yes but my web page isn't being displayed. In the code for my Product page, I start with: http://past ...

What is the best way to incorporate a jQuery script to make an engaging slideshow on my website?

I've been trying to develop a slideshow similar to the one showcased on this website. First of all: I am using Kompozer. My website is not yet live as I am still in the process of putting it together on my computer. To give you an idea, here is the d ...

What is the best way to choose a single item from an array using jQuery?

Within an array, I have IDs and descriptions like: var tablica = [{"3":"asdasd asd"},{"19":"asddas fff"},{"111111":"adas asf asdff ff"},{"4":"re"},{"5":"asdasd"},{"6":"we"},{"7":"asdasdgg"},{"9":"asdasdasd"},{"16":"sdads"},{"10":"asdgg"},{"11":"ggg"}]; ...

Loading Embedded Content with ReactJS

Currently, I am developing a one-page website with ReactJS. Each section of the site is created as individual React components, which are displayed conditionally based on the user's tab selection in the navigation bar. As part of my design, I have in ...

Can a layer be sliced to create a text-shaped cutout?

I want to achieve a cool text effect where the background is visible through the letters. I have explored options with background images and colors, but I haven't found any examples where the underlying layer is revealed. Is this even possible? Imag ...

Having trouble locating the Xpath for the download link, it appears to be listed as a list item (li). I've attempted using the Contains function without success. Any assistance would be

Seeking the Xpath for the image below. The Download File link is on the right and the element DOM is on the left. enter image description here I attempted to find the Xpath by directly copying it and also using Contains text "Download File", but my scrip ...

Avoid clicking on links while the webpage is still loading

I am facing an issue with my website where I need to intercept link-clicking events using jQuery. Everything works fine, but there is a problem if a user clicks on a link before JavaScript finishes loading, causing it to redirect to another page in error. ...

Is there a way to disregard inherited styles without relying on the use of "!important"?

Is there a way to create a new class in CSS that ignores all inherited styles without needing to use !important for each one individually? This is my HTML code: <div class="text"> <h2>Title</h2> <span>Date</span> &l ...

Challenge with Context Api state not reflecting the latest changes

Hey there, I've got this function defined in AuthContext.js: let [authTokens, setAuthTokens] = useState(null) let [user, setUser] = useState(false) let [failedlogin, setFailedlogin] = useState(false) let loginUser = async (e) => { ...

When clicking on the side-bar, it does not respond as expected

My website has a menu layout that features a logo on the left and an icon for the menu on the right side. When the icon is clicked, the menu slides in from the right side of the window, and when clicked again, it slides out. However, I am facing two issues ...