Javascript timer does not reset on Saturdays

Why does my countdown get stuck on "EXPIRED" every Saturday at 8pm (GMT+2)? Can anyone identify the issue and provide some assistance? Thank you in advance!

 function nextSaturday() {
    var d = new Date();
    console.log(d.getDay());
    if (d.getDay() == 7 && d.getHours() < 20){
      d.setHours(20);
      d.setMinutes(0);
      d.setSeconds(0);
      return d;
    }
    switch (d.getDay()) {
        case 0: d.setDate(d.getDate() + 6);
            break;
        case 1: d.setDate(d.getDate() + 5);
            break;
        case 2: d.setDate(d.getDate() + 4);
            break;
        case 3: d.setDate(d.getDate() + 3);
            break;
        case 4: d.setDate(d.getDate() + 2);
            break;
        case 5: d.setDate(d.getDate() + 1);
            break;
        case 6: d.setDate(d.getDate() + 0);
            break;
    }
    d.setHours(20);
    d.setMinutes(0);
    d.setSeconds(0);
    return d;
}

var end = nextSaturday();
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var timer;

function showRemaining() {
    var now = new Date();
    var distance = end - now;
    if (distance < 0) {

        clearInterval(timer);
        document.getElementById("countdown").innerHTML = "EXPIRED!";

        return;
    }
    var days = Math.floor(distance / _day);
    var hours = Math.floor((distance % _day) / _hour);
    var minutes = Math.floor((distance % _hour) / _minute);
    var seconds = Math.floor((distance % _minute) / _second);

    document.getElementById("countdown").innerHTML = "Countdown ends in: ";
    document.getElementById("countdown").innerHTML += days + " days ";
    document.getElementById("countdown").innerHTML += hours + " hours ";
    document.getElementById("countdown").innerHTML += minutes + " minutes and ";
    document.getElementById("countdown").innerHTML += seconds + " seconds left";

}
showRemaining();
timer = setInterval(showRemaining, 1000);

Answer №1

You've decided to end this function prematurely.

if(d.getDay() == 7 && d.getHours() < 20) { 
  d.setHours(20);
  d.setMinutes(0);
  d.setSeconds(0);
  return d; //this is where you are breaking out of the loop at 8:00 (20 hours)
}

return d; stops the function's execution and gives back the value of d

At this point, d represents this Saturday, but it should represent next Saturday, so make sure to include this:

d.setDate(d.getDate() + 7);

just before returning d.

Explanation:

The if statement above essentially means, "If it's past 8:00pm on Saturday, set d to 8:00pm on Saturday." Your code will resume working from 12:00am on Sunday when it adjusts the date to the next Saturday; you just forgot to increase the date if it's currently Saturday compared to how you handle other days of the week.

The corrected code:

if(d.getDay() == 7) { //note: I've also updated this line to reflect hour changes
  d.setHours(20);
  d.setMinutes(0);
  d.setSeconds(0);
    if(d.getHours() >= 20)
      d.setDate(d.getDate() + 7);
  return d;
}

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

Is there a way to execute a node script via command line sans the need for installation and external packages?

Is there a way to execute a node script from the command line during development without actually installing anything, but still having access to installed packages using npm install <...>? When I try node ./bin/my_script.js, the script does not reco ...

Could someone please provide clarification on this specific JavaScript syntax? I am unsure about the usage of `const {

Although I am not very familiar with javascript, I have come across this syntax and I would greatly appreciate it if someone could help me understand it! Regarding Node.js const { check, validationResult } = require('express-validator/check') ...

Transforming mp4 or Avi files into m3u8 using only node js

I'm currently exploring ways to convert a mp4 or .avi file to .m3u8 using pure node js (specifically, a Firebase Cloud Function). Does anyone have any suggestions? Thank you, but I've already attempted the following: const ffmpegInstaller = requ ...

Modifying CSS property values by handling a returned validation error

Allow me to describe a scenario I've created. Please excuse any language errors in my explanation. I have designed a form for users to submit values. Within this form, users can choose an option - one of which is "Others specify...". When this option ...

Dealing with errors while managing asynchronous middleware in Express

I have implemented an asynchronous middleware in express to utilize await for a cleaner code structure. const express = require('express'); const app = express(); app.use(async(req, res, next) => { await authenticate(req); next(); }) ...

Creating 100 unique pages using AngularJS with consistent layout

I'm currently working on an AngularJS application with two templates that are used across 100 different pages. Instead of creating separate static template files for each page, I prefer to use dynamic content within the templates. What would be the b ...

The problem with the pathLength property is causing my path animation to malfunction

I'm struggling to animate SVG graphics and haven't been able to find much information on this topic online. Recently, I attempted to animate an SVG using framer-motion in a React component. The animation configuration I used is as follows: const ...

Using Backbone: Leveraging a custom extended model when fetching a collection

Currently, I am working on developing a custom Wordpress theme using technologies like Javascript, Requirejs, and Backbonejs. As part of this process, in the index route, I have set up a new postsCollection app.postsCollection = new Posts.Collection(); to ...

Problem with JQUERY Galleria CSS positioning alignment specifically in Firefox, Chrome works without issues

I recently incorporated jquery Galleria into my website and I am currently facing an alignment issue with the div element gallery-container. Interestingly, it appears correctly aligned in Chrome but is shifted to the right in Firefox. You can view the webs ...

Struggling to store the canvas data, the file ends up blank

I've been attempting to upload an image from a canvas to a server using ajax, but every time I end up with an empty image file that is only 879 bytes. I can't seem to figure out what I'm doing wrong. If someone could take a look, I would gre ...

What makes realtime web programming so fascinating?

Working as a web developer, I have successfully created various real-time collaborative services such as a chat platform by utilizing third-party tools like Redis and Pusher. These services offer straightforward APIs that enable me to establish bidirection ...

Appending a new element to a JSON object using JavaScript

Hey there, I have a JSON object called departments. When I use console.log(departments) it displays the following data: { _id: 58089a9c86337d1894ae1834, departmentName: 'Software Engineering', clientId: '57ff553e94542e1c2fd41d26', ...

What is the process for determining the directory in which CKEditor looks for configuration and language files?

When CKEditor is loaded on a page, it searches for its configuration files relative to the location where it was initially loaded from, rather than the location of ckeditor.js. For example, loading CKEditor on the page http://www.example.com/articles/1 wou ...

Concealing a tab within a WordPress site

We have integrated a portfolio plugin with 4 categories, but we want to hide the All tab that is being displayed along with them. In order to achieve this, we need to include additional JavaScript in the header like so: (function($, undefined) { $(func ...

Text that disappears upon clicking on show/hide按钮

Could someone please help me figure out how to prevent the "See more" text from disappearing when clicked in the example below? I want it to stay visible. Thank you! ...

Providing a public API that exclusively grants access to requests originating from my own website

After hours of scouring Google and SO, I have yet to find someone facing the same challenge I am encountering now. Here's the situation: We have invested a significant amount of money and effort into maintaining a database. The data from this databas ...

Executing a Node.js script using an absolute path

In the process of developing a basic app using Node.js and Express, I've encountered an issue. The script is located at path/to/script/server.js. When I run this script with node server.js while in the correct directory, everything functions correctly ...

Transform a list separated by commas into JSON format using Javascript

Is there a way to transform a comma separated list into json using Javascript or jQuery? For example: Take this list: var names = "Alice,Bob,Charlie,Dave,"; and turn it into: var jsonified = { names: [ {name: "Alice"}, {name: "Bob"}, ...

Splitting the express instance and routes into two separate server files

Currently, I am in the process of developing a middleware that can run two server files within the same instance while keeping the routes separate. Allow me to elaborate with examples: Directory Structure: /common-server /routers /routes.js /ap ...

Pusher: Received no callbacks for testing the pusher functionality on my event

I am attempting to implement a feature where each object I create is broadcasted without the need to refresh the page. Below is the JavaScript code for initializing Pusher and binding the event for UserHasRegistered: <script src="https://js.pusher. ...