In JavaScript countdown timer, incorporate a leading zero to the minutes and seconds

I'm struggling to incorporate leading zeros into the minutes and seconds of this javascript countdown timer. I can't seem to make the leadingzero function work properly. The additional leadingzero function that I added doesn't appear to be functioning as intended:


<pre><html>
    <head>
    </head.
    <body>

        <p style="font-size:100px;">

            <div id="countdown"></div> </p>
            <div id="notifier"></div>
            
            <script type="text/javascript">

                function display( notifier, str ) {
                    document.getElementById(notifier).innerHTML = str;
                }

                function toMinuteAndSecond( x ) {
                    return Math.floor(x/60) + ":" + x%60;
                }

                function setTimer( remain, actions ) {
                    (function countdown() {
                        display("countdown", toMinuteAndSecond(remain));         
                        actions[remain] && actions[remain]();
                        (remain -= 1) >= 0 && setTimeout(arguments.callee, 1000);
                    })();
                }

                function leadingzero(setTimer) {
                    if  (setTimer < 10 && setTimer >=0) 
                        return '0' + setTimer;
                    else
                        return setTimer ; 
                }

                    
                setTimer(600, {
                    10: function () { display("notifier", "Just 10 seconds to go"); },
                    5: function () { display("notifier", "5 seconds left"); },
                    0: function () { display("notifier", "Your access is no longer guaranteed.. you need to refresh your page to gain another spot"); }
                });   
             </script>
          </body>
     </html>

</pre>

Answer №1

function convertMinutesToSeconds( x ) {
    minutes = Math.floor(x/60)
    seconds = x%60
    result = ((minutes>0) ? ((minutes>9) ? minutes : '0'+minutes) + ":" : "") 
    result += (seconds>9 || minutes == 0) ? seconds : '0'+seconds;
    return result
}

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

Redirecting using REACTJS with a 5-second delay

Just dipping my toes into the world of reactjs, and I'm stuck on a little problem. I'm attempting to create a webpage that automatically redirects after 5 seconds, but I can't quite crack the code. Any advice or resources on how to accomplis ...

Is there a way to locate and refine the blogs associated with a specific user?

Check out the following blog entries stored in the Database: [ { _id: 5fec92292bbb2c32acc0093c, title: 'Boxing ring', author: 'T. Wally', content: 'boxing stuff', likes: 0, user: { _id: 5fd90181 ...

Determine the dimensions of Expo's React Native Over the Air (OTA) update

Is there a method to determine the size of the required download for an OTA update before existing deployed apps (e.g. v1) retrieve it following the publication of a new managed Expo app (e.g. v2)? ...

Incorporate a class into the fixed navigation menu using fullpage.js

I am attempting to modify the behavior of a sticky menu as the user scrolls down using fullpage.js. My goal is to have the #top-wrapper behave normally when the first section/page loads, and then add a class of is-fixed as you scroll down. When scrolling ...

Converting a decimal Unicode to a string in Javascript/Node: a beginner's guide

In my database, I have Arabic sentences that contain decimal unicodes for quotation marks and other elements. For example, here is a sample text: "كريم نجار: تداعيات &#8220;كورونا&#8221; ستغير مستقبل سوق السي ...

Configuration and debugging of UI Router

I'm implementing ncy-angular-breadcrumb with UI routes. I have a module dedicated to hosting the UI routes: (function () { var app = angular.module('configurator.uiroutes', ['ui.router', 'ncy-angular-breadcrumb']); ...

Limiting the number of files that can be uploaded using ng-file-upload in Angular.js is a simple process

Can someone help me with limiting file selection using ng-file-upload in Angular.js? Here is my code: <input type="file" class="filestyle form-control" data-size="lg" name="bannerimage" id="bannerimage" ng-model="file" ngf-pattern="' ...

Is there a way to use setTimeout in JavaScript to temporarily stop a map or loop over an array?

data.forEach((d, i) => { setTimeout(() => { drawCanvas(canvasRef, d); }, 1000 * i); }); I have implemented a loop on an array using forEach with a one-second delay. Now I am looking to incorporate a pause and resume f ...

Implement a shaking animation for a div when the input fields are not valid

Does anyone know how to make these divs shake when the inputs are not valid (or empty)? Here is a link to what I have tried so far: http://jsfiddle.net/jalxob/ahQLC/13/ I attempted to accomplish this by using: .effect('shake'); If anyone h ...

The dynamic styles set by CSS/JavaScript are not being successfully implemented once the Ajax data is retrieved

I am currently coding in Zend Framework and facing an issue with the code provided below. Any suggestions for a solution would be appreciated. The following is my controller function that is being triggered via AJAX: public function fnshowinfoAction() { ...

What could be the reason for the lack of read or write functionality in $cookies for angular version 1.6.6?

I am relatively new to working with Angular. I have started a test project and my goal is to store user authentication in cookies. Despite my best efforts, I keep encountering an undefined error when attempting to retrieve the stored value. I am not sure w ...

Steps for identifying the file format of a document with JavaScript

Can someone assist me in determining a file type using JavaScript within the context of this HTML code? <div class="indi-download"> <div class="pull-left"> <h6 class="file-format">%file_display_name%</h6> </div> <div c ...

Tips for adding an image into a PDF document using the jsPDF library in HTML

Due to the lack of support for utf8 characters in jspdf, I'm experimenting with replacing some characters with images before exporting to pdf. To illustrate, I've created a code sample where I insert an image into an html div and then attempt to ...

Using JavaScript to call an API in PHP and determine how to handle a response that is not equal to 200 by printing an

Greetings! I am aiming for a scenario where, upon clicking the link, the user's parameter is transferred to JavaScript. This parameter will then be used in ajax to trigger a call to my PHP file containing the API. The API, after processing the parame ...

The absence of localStorage is causing an error: ReferenceError - localStorage is not defined within the Utils directory in nextjs

I've been trying to encrypt my localstorage data, and although it successfully encrypts, I'm encountering an error. Here's the code snippet (./src/utils/secureLocalStorage.js): import SecureStorage from 'secure-web-storage' import ...

Picture is unavailable for viewing - (Express, Pugjs)

I'm having trouble getting an image to display on my page using a pug template. Despite following the setup and files correctly, the image still isn't showing up. Here is what I have: index.js app.use('/images', express.static(path.r ...

Trouble with displaying class object array in Angular 5 using ngFor loop

I am attempting to loop through an array of class objects to populate a dropdown menu in Angular 5. However, the dropdown menu is not showing any options and there are no errors appearing in the browser console. The object array is created based on this m ...

An anchor-shaped name tag with a touch of flair

I stumbled upon this unique anchor name design on the website Does anyone here know how to create something similar? What is that style called? ...

Steps to fix the error message "Unable to access properties of null (reading 'toLowerCase')"

I encountered an error while working on my React project, and I need assistance to resolve it. The error message is: Cannot read properties of undefined (reading 'toLowerCase') App.js import "./App.css"; import Navbar from "./Com ...

HTML Buttons Remain Selected After Being Clicked

Currently working on a calculator app for a class project but I've hit a roadblock while setting up keyboard listeners. The keyboard functionality is fine, however, when it comes to clicking on buttons, specifically the non-keyboard functions, they re ...