Timer Does Not Appear to be Counting Down

I recently added a countdown clock to my website, but I'm having an issue with it not updating in real-time unless the page is refreshed. I'm not very familiar with javascript, so I found some code online and made some modifications myself to suit my needs. Is there something missing or incorrectly formatted in the code that could be causing the countdown to not update in real-time?

function updateTimeSpan() {
  var theSpan = document.getElementById('timeLeft');
  var d = new Date();
  var t = new Date();
  var ms;
  var s, m, h;

  // if it's after 5pm, set today to tomorrow    
  if (d.getHours() > 16) {
    d.setDate(d.getDate() + 1);
  }
  // get the next monday    
  while (d.getDay() != 1) {
    d.setDate(d.getDate() + 1);
  }
  // set the time    
  d.setHours(1665);
  d.setMinutes(33);
  d.setSeconds(27);
  // get the difference between right now and next monday    
  ms = d - t;
  // get the days between now and then    
  d = parseInt(ms / (1000 * 60 * 60 * 24));
  ms -= (d * 1000 * 60 * 60 * 24);
  // get hours    
  h = parseInt(ms / (1000 * 60 * 60));
  ms -= (h * 1000 * 60 * 60);
  // get minutes    
  m = parseInt(ms / (1000 * 60));
  ms -= (m * 1000 * 60);
  // get seconds    
  s = parseInt(ms / 1000);
  theSpan.innerHTML = d + ' DAYS | ' + h + ' HRS | ' + m + ' MINS | ' + s + ' SECS';
  setTimeout('updateTimeSpan()', 100);
}

onload = updateTimeSpan();

$(function() {

  $("h2")
    .wrapInner("<span>")

  $("h2 br")
    .before("<span class='spacer'>")
    .after("<span class='spacer'>");

});
.timer-header {
  position: absolute;
  left: 0;
  width: 100%;
}

.timer-header span {
  color: black;
  font: bold 24px/45px Montserrat, Sans-Serif;
  letter-spacing: -1px;
  font-size: 30px;
  padding: 10px;
}

.timer-header span.spacer {
  padding: 0 5px;
}

@media only screen and (max-width: 480px) {
  .timer-header span {
    color: black;
    font: bold 24px/45px Montserrat, Sans-Serif;
    font-size: 18px;
    padding: 5px;
  }
  .timer-header span.spacer {
    padding: 0 5px;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
  <h2 class="timer-header"><span id="timeLeft"></span></h2>
</body>

Answer №1

Give this a try

var countDownDate = new Date("Jan 5, 2020 00:00:00").getTime();


var x = setInterval(function() {

  var now = new Date().getTime();
    
  var distance = countDownDate - now;
    
  // Calculating days, hours, minutes and seconds
  var days = Math.floor(distance / (1000 * 60 * 60 * 24));
  var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);
    
  document.getElementById("demo").innerHTML = days + "d " + hours + "h "
  + minutes + "m " + seconds + "s ";
    
  // Displaying status when countdown is over
  if (distance < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
  }
}, 1000);
p {
  text-align: center;
  font-size: 60px;
  margin-top: 0px;
}
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

<p id="demo"></p>
</body>
</html>

Answer №2

If you need to continuously update a value at regular intervals, consider using the setInterval method.

function updateValueOverTime() {

}

window.onload = function() {
  setInterval(updateValueOverTime, 100);
}

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

Execute multiple events using jQuery's .trigger() method

As I develop a jQuery plugin, I am utilizing the .on and .trigger functions for my pub/sub system. One challenge I am facing is triggering multiple events in different scenarios with ease. My question is whether it is possible to trigger multiple events a ...

Guide to organizing files with custom directory layout in NodeJS

Imagine having multiple files spread across various folders. /parentDir/ |__dirA/ |__file1 |__file2 |... |__dirB/ |__file3 |... |... You want to consolidate them into an archive, with the option of using something like ...

Correcting W3C validation issues is essential

I am encountering errors in my W3C validation process. Even though I have set <!DOCTYPE HTML> for my page, I continue to experience issues as shown in the image below. I have been trying to troubleshoot and resolve these errors without much success ...

Is there a way to prevent ng-template-loader from scanning image src's?

Currently, I am beginning to incorporate webpack into my development workflow for an angular project. To create my templateCache, I have had to include the ng-template-loader. Below is a snippet of my webpack configuration: { test: /\.html$/, loa ...

Problems with the firing of the 'deviceready' event listener in the PhoneGap application

Utilizing vs2012, I have been working on a PhoneGap application. Within this application, the following JavaScript code is being used: document.addEventListener("deviceready", onDeviceReady, false); function onDeviceReady() { // alert("hh") ...

Trigger a page refresh using a popup

Exploring the world of React for the first time has been quite a journey. I've encountered a hurdle in trying to force my page to render through a popup window. The setup involves a function component with a popup window that allows text changes on t ...

What's the best way to add two distinct colors as background for a header with css?

h2 {background-color:#C61236; color:#FFFFFF; font-size:medium; line-height:1.5; text-indent:20px;} Although the current setup looks good, I am looking to incorporate a new color block at the start of the text. I'm not sure what steps to take nex ...

Using Jquery to duplicate a row from one table and insert it into another table

Recently, I've dived into the world of jQuery and JavaScript with the goal of creating a simple app. The main functionality I'm trying to implement is the ability to copy a row from one table to another and then delete the original row when a but ...

Navigating through different components within a single page

Each segment of my webpage is a distinct component, arranged consecutively while scrolling e.g.: <sectionA></sectionA> <sectionB></sectionB> <sectionC></sectionC> All the examples I've come across involve creating ...

Angular2 Error: Cannot have two identifiers with the same name, 'PropertyKey' is duplicated

I am currently developing an application with angular2 using angular-cli. Unfortunately, angular-in-memory-web-api was not included by default. After some research, I manually added the line "angular-in-memory-web-api": "~0.1.5" to my ...

Mastering the art of obtaining XPaths through Selenium WebDriver

While working on test automation for a section of Outlook Web App, I focused on checking a designated test mailbox that receives emails from our company. I needed to verify specific texts within an email using Assert, but encountered difficulty in identify ...

What could be the reason behind the for loop not incrementing and the splice not being modified in my code?

Encountered a seemingly simple problem while coding, but the expected returns started deviating as I progressed. Your assistance would be greatly appreciated. If you do provide help, please elaborate on your approach and where I hit a roadblock. The Chal ...

How to use $$[n] in Spectron/WebdriverIO to target the nth child element instead of the selector

Attempting to utilize Spectron for testing my Electron application has been challenging. According to the documentation, in order to locate the nth child element, you can either use an nth-child selector or retrieve all children that match a selector using ...

Issues with the functionality of the map method in Javascript arrays

I have integrated Laravel and Vue.js to develop a chat application. To secure my response in Laravel, I implemented encryption to prevent unauthorized access from the console: public function get() { $contacts = User::where('id', '!=&ap ...

IconButton function in ReactJS malfunctioning specifically in Firefox browser

There seems to be an issue with the click function of IconButton from Material UI not working in any version of FireFox. Below is the code snippet in question: <div className='floating-button visible-xs'> <IconButton touch={true} tool ...

Fade the current Div out and fade in the following Div while also animating its child element

Looking to achieve a fade in and out effect for 3 divs, with the child element animating its way up from the bottom right once the divs have faded in. I've been working on it but haven't made much progress, does anyone have any ideas? Check out ...

Is there a way to incorporate a CSS file into this without explicitly mentioning the color?

I have successfully implemented a PHP solution for changing themes with a cookie that remembers the selected theme color when the user leaves the site. However, I now need to switch this functionality to JavaScript while still utilizing the CSS file. How c ...

Guide on invoking a JavaScript function within a jQuery upon a specific event, such as clicking a hyperlink

I have a website page where I display some important information. However, I want to make this text hidden initially and only visible when a user clicks on a specific link or button. I attempted to achieve this functionality using the following code snippe ...

The parameters in VueJS are malfunctioning on this webpage

I created my vue in an external file and included it at the bottom of my webpage, but I am encountering issues with its functionality. One specific problem arises when using v-model, resulting in a template error displayed on the page: Error compiling t ...

Text input fields failing to record text

I've set up a forum using react-redux and material ui, but I'm facing an issue where the text fields are not updating based on state changes. When users try to type in the text field, nothing seems to happen. onChange={e => onT ...