The Arrival of Link: A Countdown Timer

I'm attempting to create a countdown timer that reveals a link after 20 minutes. Currently, this is my progress...

    <script type="text/javascript">

window.onload = function()
{
    countDown('my_div1', '<a href="cdtl.html">Hello 1</a>', 720);
}

function countDown(elID, output, seconds)
{
    document.getElementById(elID).innerHTML = (seconds==0) ? output : 'Time until link appears: ' + seconds;
    if(seconds==0) { return; }
    setTimeout("countDown('"+elID+"', '"+output+"', "+(seconds-1)+")", 1000);
}
</script>

The functionality is there, but I have a specific goal in mind. How can I modify the countdown to display as 20:00:00 instead of 720 seconds?

Answer №1

Shehabix provides an answer to your question, however, I suggest the following code rewrite:

window.onload = function() {
    countDown('my_div1', '<a href="cdtl.html">Hello 1</a>', 720);
}
function countDown(elID, output, seconds) {
    var elem = document.getElementById(elID),
        start = new Date().getTime(), end = start+seconds*1000,
        timer = setInterval(function() {
            var now = new Date().getTime(), timeleft = end-now, timeparts;
            if( timeleft < 0) {
                elem.innerHTML = output;
                clearInterval(timer);
            }
            else {
                timeparts = [Math.floor(timeleft/60000),Math.floor(timeleft/1000)%60];
                if( timeparts[1] < 10) timeparts[1] = "0"+timeparts[1];
                elem.innerHTML = "Time left: "+timeparts[0]+":"+timeparts[1];
            }
        },250); // setting a lower number for increased timer accuracy, 250 is recommended
}

This rewritten code will operate more efficiently by utilizing functions instead of relying on eval when passing a string to setTimeout. It also incorporates delta timing to calculate the remaining time accurately since specifying milliseconds isn't precise due to the processing time delay.

Answer №2

At the outset, let's clarify that 7200 seconds equal 120 minutes, not 20;

Now, in reference to the 20 minutes: XX seconds

var remainingMinutes = Math.floor(seconds / 60);
var remainingSeconds = seconds - (remainingMinutes * 60);

document.getElementById(elID).innerHTML = (seconds==0) ? output : 'Time until link appears: ' + remainingMinutes + "minutes and "+remainingSeconds+" seconds";

Alternatively, if you prefer the output in MM:SS format:

you can use this method:

document.getElementById(elID).innerHTML = (seconds==0) ? output : 'Time until link appears: ' + remainingMinutes + ":"+remainingSeconds;

Answer №3

It is important to note that relying on this method for high security is not recommended, as the source code can be easily read and the link deciphered. Even with obfuscation, determined individuals can still decode it if the browser is capable of doing so.

var twentyMins = 20 * 60; // Calculating 20 minutes in seconds

window.onload = function() {
    countDown('my_div1', '<a href="cdtl.html">Hello 1</a>', twentyMins);
}

function countDown(elID, output, seconds) {
    var mins,
        secs = seconds,
        pad = function (n) {
            return n > 9 ? n : '0' + n;
        };

    hours = Math.floor(secs / 3600); 
    secs %= 3600;
    mins = Math.floor(secs / 60);
    secs %= 60;

    secs = pad(secs);
    mins = pad(mins);
    hours = pad(hours);

    document.getElementById(elID).innerHTML = (seconds === 0) ? output : 'Time until link appears: ' + hours + ':' + mins + ':' + secs;

    if (seconds !== 0) {
        seconds -= 1;
        setTimeout(countDown, 1000, elID, output, seconds);
    }

}

View jsFiddle demo here

Instead, using setInterval rather than setTimeout would be a more reliable approach. Timers are unpredictable due to varying delays, which can affect the execution timing. Using setInterval allows for consistent updates without potential disruptions caused by alerts or background processes.

The modern environment of browsers may also impact timer accuracy, making timer resolutions fluctuate. Implementing setInterval mitigates these issues and ensures smoother countdown functionality.

var twentyMins = 20 * 60; 

window.onload = function() {
    countDown('my_div1', '<a href="cdtl.html">Hello 1</a>', twentyMins);
}

function countDown(elID, output, seconds) {
    "use strict";
    var timer, 
        el = document.getElementById(elID),
        getTime = function () {
            return (new Date()).getTime();
        },
        finishAt = getTime() + (seconds * 1000),
        pad = function (n) {
            return n > 9 ? n : '0' + n;
        },
        lastCount = -1,
        update = function () {
            var hours,
                now = getTime(),
                mins,
                secs = Math.floor((finishAt - now) / 1000);

            if (lastCount !== secs) {

                lastCount = secs;

                if (now >= finishAt) {
                    clearInterval(timer);
                    el.innerHTML =  output;
                } else {
                    hours = Math.floor(secs / 3600); 
                    secs %= 3600;
                    mins = Math.floor(secs / 60);
                    secs %= 60;
                    secs = Math.floor(secs);

                    secs = pad(secs);
                    mins = pad(mins);
                    hours = pad(hours);

                    el.innerHTML = 'Time until link appears: ' + hours + ':' + mins + ':' + secs;
                }
            }
        };

    update();

    timer = setInterval(update, 499);
}

Check out the updated version on jsFiddle

In both solutions provided, the remainder operator was used for calculating time components due to its efficiency compared to alternative methods. Additionally, employing strict equality operators enhances performance and conforms to coding best practices.

Enhanced features in the improved solution include storing previous counts to minimize redundant calculations and DOM accesses. Utilizing setInterval optimizes the countdown process and reduces inaccuracies stemming from browser nuances.

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

Auth0 encountering issues retrieving ID token and user metadata

Currently in the process of integrating Auth0 into a Vue.js/Node.js application, I have successfully enabled user registration and login functionality (to /callback). Although the manual addition of data to the user metadata section is functional at this s ...

Activate Pop-up for a single instance on BigCommerce

After researching and adding my own code, I am still struggling to get this question answered correctly. Here are the key points I am trying to achieve: 1. Automatically open a popup when the homepage loads. 2. Ensure that the popup is centered on all brow ...

The attention remains fixed at the top of the page

I have implemented an update panel along with pagination links using a repeater control at the bottom of my page. However, I am encountering an issue where clicking on the pagination links does not bring the page to the top. I attempted to use the followin ...

The issue with hiding and showing elements using JavaScript during drag and drop functionality

In my code, I have two boxes with IDs box1 and box2, These boxes can be dragged and dropped into the boxleft element, Upon dropping them, the background image is removed and only the name appears in the box, My issue is that when loading values into box ...

Encountered an issue during the creation of a Nuxt.js project using the command line tool, where a SyntaxError was triggered

I encountered an issue while attempting to set up a nuxt.js starter project using the nuxt cli. Here are the steps I followed: Installed vue cli globally with the command: npm install -g vue-cli Created the project using: vue init nuxt-community/star ...

Inserting a file read using Node.js into a MongoDB database

Recently, I came across a text file that contains the following data: title: A, alert: notice, desc: Starting title: B, alert: notice, desc: Process Step 1 and 2 Step 1 - Execute Step 2 - Log title: C, alert: notice, desc: "Ending" My goal is to insert ...

Ensure the text value of a collection of web elements by utilizing nightwatch.js

Recently, I started using nightwatch.js and I am trying to retrieve a list of elements to verify the text value of each element against a specific string. Here's what I have attempted: function iterateElements(elems) { elems.value.forEach(funct ...

Vue component encounters undefined error when passing prop array through component

My challenge is passing an array of dates to my component, but I keep encountering this error: [Vue warn]: Property or method "dates" is not defined on the instance but referenced during render I'm puzzled by this issue because I am receiving the ...

Organizing Results into Divs Based on Column Value Using AngularJs

I've been racking my brain trying to figure out the best way to organize and display my results in separate divs, specifically using Bootstrap col-md-4's. This is for a chat messaging app that I'm in the process of developing. I have rooms a ...

SailsJS - handling blueprint routes prior to configuration of routes

I am trying to configure a route in my config/routes.js file as shown below '*' : { controller: 'CustomRoutes', action: 'any', skipAssets:true } The CustomRoutes controller is responsible for handling custom routes. Th ...

Is it possible to dynamically override inline styles?

My HTML code is as follows: <div title="remove css"style="position:relative;">Remove my style</div> After the page loads, I need to completely remove the position style attribute. Due to limitations, I cannot override the CSS. Is there a way ...

Steps to display the Sidebar on top of the main information page

One unique feature of my website is the FiltersSideBar located on the left side of the page. It contains various filters to refine search results. To optimize user experience, I implemented a function that hides the sidebar at specific browser window size ...

What causes JavaScript image to stop loading while displaying a prompt dialog?

I have nearly finished my project. I will include a codepen link at the end of the post for debugging purposes. What Should Happen? The img element has an id property of dragon, and the image specified in the src attribute should be pre-loaded as the defa ...

Utilizing a function within a span element

Can anyone help me figure out what I'm doing wrong while trying to toggle between a span and an input text field using the on function? If you want to take a look, I've created a fiddle for it here User Interface <div> <span >My va ...

Anticipated spatial glitch problem involving the gadicc/meteor-reactive-window package for Meteor

Utilizing the gadicc/meteor-reactive-window Meteor Package to switch templates based on screen size. This file is named pictureDisplatSection.html <template name="pictureDisplaySection"> <div class="display"> ...

Is it possible to include 'file.php' along with the 'id' using php?

I have constructed my website using php include and the structure of the index is as follows: Menu.php (menu system) main.php (Main page) footer.php (footer section) On the main.php (main page), I have incorporated a news script that utilizes $_GET t ...

Enhance your Next JS website's SEO with a combination of static pages, SSR pages, and client-side

In my project using Apollo GraphQL with Next JS, I have explored three different approaches to querying and rendering data. The first method involves Static Rendering by utilizing getStaticProps(), which looks like the following: export async function getS ...

Preventing the keyboard from showing on mobile devices when using a React date time picker

I am currently utilizing the React-date-picker component in my ReactJS application. I am encountering an issue where the keyboard is appearing along with the date picker when testing on mobile devices. I have attempted some solutions, but none have resol ...

Is the click count feature malfunctioning?

My goal is to track every mouse click made by the user, so I created a function for this purpose. However, it seems that the function is only counting the first click. To store the count values, I have created a variable. <!DOCTYPE html PUBLIC "-//W3 ...

Utilizing conditional statements like if/else and for loops within a switch statement in JavaScript allows for

I am currently developing a request portal that involves dynamic checkboxes, labels, and textboxes that are dependent on an option list. As a beginner in javascript, I am facing challenges with creating conditional statements. I have managed to make progr ...