Why do my countdown codes start displaying negative numbers?

function StartTime() {
  var currentTime = new Date();
  var hoursRemaining = 19 - currentTime.getHours();
  var minutesRemaining = 60 - currentTime.getMinutes();
  var secondsRemaining = 60 - currentTime.getSeconds();
      timeLeft = "  " +hoursRemaining+'      '+minutesRemaining+'      '+secondsRemaining+' ';
  $("#countdown").html(timeLeft);
}

var countdown;
function StopTime() {
    clearInterval(countdown);

}

setInterval(StartTime, 1000);

It's currently 8:30pm here and I want the countdown to restart at 9pm. It should reset every day at 9pm, even if it goes into negative numbers.

Answer №1

function DisplayCountdown() {
        var currentTime = new Date();
        var hoursLeft;
        var currentHours = currentTime.getHours();
        
        if (currentHours > 19) {
            hoursLeft = 24 - currentHours + 19;
        } else {
            hoursLeft = 19 - currentTime.getHours();
        }
        
        var minutesLeft = 60 - currentTime.getMinutes();
        var secondsLeft = 60 - currentTime.getSeconds();
        
        var countdownDisplay = "  " + hoursLeft + '   & ' 
                               + minutesLeft + '    & ' + secondsLeft + ' ';
        
        $("#countdown").html(countdownDisplay);
    }

Answer №2

To properly utilize the clearInterval function, make sure to assign a value to countdown:

countdown = setInterval(ShowTime ,1000);

Answer №3

Can you please structure the process in the following manner?

If the current time is greater than 19, then
calculate the time left as (24 - now) + 19
otherwise, determine hours as 19 - now;

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

Conceal / Modify / Incorporate a picture

My ultimate goal is to have a hidden box and image that will be revealed based on the result of other functions. The box should change its background color, display an image, and switch images depending on the function called. I am facing two issues with ...

How to Retrieve Checkbox Values from Multiple Rows Using JavaScript

I have a variety of module rows that allow users to manage access rights by selecting specific options. My goal now is to extract the checked boxes from these checkboxes with the name "config{{$field->id}}". Below is the current functioning code. HTM ...

Learn how to simultaneously play two audio files using the same identifier in JavaScript

I'm facing an issue with two audio files that have a progress bar and both have the same ID: <audio id="player" src="<?=base_url('mp3/'.$rec->file)?>"></audio> </p> ...

What is the best way to change the value of an array within a ref in Vue 3?

Currently, I am in the process of developing a Vue.js application. Within my code, there is a reference variable that holds an array. My goal is to update a specific value within this array. export default defineComponent({ setup() { const allQues ...

Using JavaScript arrays to populate an HTML form

I am new to JavaScript, although I have some experience with Python, and I find it challenging to integrate JS with HTML. I am attempting to convert an array into an HTML dropdown list, but I am struggling to make it function correctly. <HEAD> ...

Arrange the data in the table to ensure that it is organized neatly into the appropriate columns

I am currently working on a project that involves creating a table to display user answers for purchased tickets under the corresponding questions. If a question has not been answered, I want to show a dash symbol instead. However, I am encountering an is ...

Using jQuery along with the jQuery Form Plugin to retrieve and parse the plain text responseText from an Ajax

I am currently working on creating a form using ajaxForm from the jQuery Form Plugin. var options = { target: '#output', // target element(s) to be updated with server response beforeSubmit: beforePost, // pre-submit cal ...

jQuery unable to locate elements or update class following AJAX response

My jQuery.on() event functions are working great when bound to specific elements like "a.my-link". However, I have one function that is bound to the document or body and then traverses multiple elements with the same class attribute. Certain lines in this ...

Is there a way to use Javascript or JQuery to conceal all unchecked items in a RadioButtonList?

Currently, I am utilizing the Asp .net repeater to bind the selected value in the RadioButton list. Here is an example snippet: <asp:RadioButtonList ID="RadioButtonList1" runat="server" SelectedValue='<%# Eval("Numbers& ...

Utilize the power of PIXI.js to effortlessly convert your canvas into a high-quality image without encountering

I'm currently working on exporting the entire canvas as a PNG using PIXI.js within a React app that incorporates react-pixi. My version is 6.5 and I've been trying out the following code: // MyComponent.tsx <button onClick={exportImage} /> ...

Slider MIA - Where Did it Go?

I'm having an issue with my slider. When I load the page, it doesn't show the first image until I click the button to load it. How can I make it display the first image by default? Below is my JavaScript code: <script> var slideIndex = 1 ...

Updating during an ongoing state transition is not possible, especially within the `render` method. The `render` method should strictly be a pure function based on the props and state provided

Currently, I am utilizing react and react hooks for the front-end development of my project. Unfortunately, I have encountered an error message that states: index.js:1 Warning: Cannot update during an existing state transition (such as within `render` ...

The CORS problem arises only in production when using NextJS/ReactJS with Vercel, where the request is being blocked due to the absence of the 'Access-Control-Allow-Origin' header

I've encountered a CORS error while trying to call an API endpoint from a function. Strangely, the error only occurs in production on Vercel; everything works fine on localhost. The CORS error message: Access to fetch at 'https://myurl.com/api/p ...

Sending images as a base64 string from a Titanium app to a Ruby on Rails web service

I am encountering an issue when trying to upload an image from an app that has been converted into a base64 string to a Ruby on Rails server. The app is developed using Titanium. However, after retrieving and decoding the image string back into an image, ...

Is there a way to accelerate the webpack bundling process when using React during development?

Forgive me for what may seem like a silly question, but I am just beginning to explore the world of JavaScript and React. In my project, I am using React on the frontend and Django on the server side. Currently, I am unable to use React routing, so I have ...

Comprehend the angular and in a confined scope and its brackets

I have been wondering why I have to use double brackets ()() when passing a method from an outer scope to a directive with an isolated scope using '&'. It seems like the function is returned with callThat() and then I need to call it with anothe ...

Is it possible to use a JavaScript string as a selector in jQuery?

So, my issue is with the following JavaScript code snippet: for ( i=0; i < parseInt(ids); i++){ var vst = '#'+String(img_arr[i]); var dst = '#'+String(div_arr[i]); } I'm wondering how I can proceed in jQuery to handle ...

Is it possible that using npm link could be the root cause of the "module not

As I delve into understanding how to utilize TypeScript modules in plain JavaScript projects, it appears that I am facing a limitation when it comes to using npm linked modules. Specifically, I can successfully use a module that is npm-linked, such as &apo ...

Determine the height of an element in JavaScript or jQuery by using the CSS property height: 0;

I'm facing a challenge in determining the actual height of an element, which currently has a CSS height property set to: height: 0; When I check the console, it shows a height of 0, but I'm looking to find the real height of the element. I als ...

`Stop the JW Player from playing several videos simultaneously`

I have a situation where I want to display multiple videos on the same page, but only one should be playable at a time. When a new video is started, the currently playing video should automatically stop. <div class="tab-pane active" id="abc"><d ...