Building a Timekeeping Tool with Javascript

I am interested in creating a timer/stopwatch using JavaScript for a specific scenario:

When the user clicks the "Play" button, the stopwatch will start counting, and when they click "Pause," it will stop. The difference between the start and end times will give me the elapsed time. I want to display this as the progress time of a song and update it accordingly. If the song has finished playing, the timer should reset to 0; otherwise, it should resume from where it was paused. Can you please provide guidance on how to achieve this functionality in JavaScript? How can I retrieve the current time (using getTime perhaps)?

Thank you,
Sneha

Answer №1

To display the current position of an audio file being played, you can utilize the currentTime attribute of the audio element. This attribute is automatically updated with the pointer's location.

On the other hand, a simple stopwatch functionality involves recording new Date().getTime() when it starts, and then recording it again when it stops to calculate and return the time difference.

Answer №2

Consider implementing the following approach:

document.getElementById('start').onclick = function() { window.started = +new Date(); }
document.getElementById('stop').onclick = function() {
    var duration = (+new Date() / 1000) - window.started / 1000 < sessionDurationInSeconds;

    if (duration > sessionDurationInSeconds)
        // reset to beginning of session
    else
        // continue from where left off
}

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 insert a label directly following a dropdown menu within the same table cell?

My goal is to include drop-down lists in a web page, so I decided to create a table structure using JavaScript. Firstly, I used the document.createElement() method to generate a table, table body, rows, and cells. Then, I proceeded to create select element ...

Learn how to insert a <TableRow> in a for loop using Object.keys

<TableBody> {(() => { var result = []; let key = Object.keys(genericResultList)[1]; var list = genericResultList[key]; for (var i = 0; i < list.length; i++) { ***\<!-- Add in the \<T ...

The ASP.net PageMethods are returning an undefined value

Hello everyone, I am attempting to retrieve data from C# to JavaScript using ToolkitScriptManager. Here is my ASPX code: <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script src=" ...

JavaScript - Issue with retrieving object properties accurately

Here is a code snippet that I am working with: function retrieveObjects(name, data) { return data.filter(function(d) { return name.title == d.title; }).map(function(d) { return { "title": d.title, "sort": d. ...

The function JSON.parse appears to be malfunctioning within the code, yet it operates smoothly when executed in

I am facing an issue with my Angular $http post service that communicates with a WCF service. The success handler in the http post is as follows: .success(function (data) { var response = JSON.parse(data); var tsValid = response.Outcome; defer ...

The method you are trying to call is not defined in Laravel

I recently developed a basic CRUD blog application with tags functionality. I have integrated tags into my pages and implemented the use of Select JS for selecting and editing tags in input fields. Now, my goal is to have the input field pre-populated wit ...

What are some strategies to enhance the responsiveness of this JQuery code?

I'm facing an issue while trying to create a progress bar that dynamically adjusts based on the device's width. In this particular scenario, whenever the device width changes, the progress bar's width remains static, causing it to break whe ...

Is there a way to direct to a specific URL upon clicking a button using PHP?

In my PHP code called registerprocess.php, it executes after clicking a submit button on another page named userregistration.php. If a user tries to register with an email that already exists in the database, I want registerprocess.php to redirect back to ...

What is the process for defining custom properties for RequestHandler in Express.js middleware functions?

In my express application, I have implemented an error handling middleware that handles errors as follows: export const errorMiddleware = (app: Application): void => { // If the route is not correct app.use(((req, res, next): void => { const ...

Debugging on the server side of Meteor application is crucial for

I am attempting to debug a Meteor app on Windows using node-inspector. I am following these steps: First, install node-inspector by running: npm install -g node-inspector Next, start Meteor in debug mode by running: NODE_OPTIONS='--debug' meteo ...

Retrieve the file name (as well as other properties) when clicking on an image in dropzone.js

Is there a way in dropzone.js to retrieve the file name of an uploaded image when it is clicked? Check out this resource for more information: ...

Finding the nearest span value upon clicking through a specific class

Whenever a user clicks on a hyperlink, my goal is to locate the nearest span element with a specific class and retrieve the text within that class. As of now, it is only returning blank text: Here is the provided HTML code snippet: <div class="plan re ...

JavaScript: What is the best way to increase the size of an array by adding new elements

I am attempting to generate an array containing the first 100 prime numbers. Here is the code I have written: var primeArray= []; var num= primeArray.length; function checkIfPrime(n) { if(n < 2) { return false; } for(i=2; i< ...

Issue with JQuery: object.id is returning as undefined even though it should have a value

While working with JQuery, I encountered a rather peculiar (or possibly foolish) error. The HTML code snippet in question is as follows: <input type="password" name="repeatPassword" id="id_repeatPassword" /> And within my javascript code, I have t ...

Is there a comparison you can make between v-for and a similar feature in Stencil? (such as a functionality akin to v-for

When working with arrays in Stencil, I need to repeat a specific element multiple times based on the array. In Vue, I typically use v-for for this purpose, but what is the equivalent in Stencil? ...

Automatically submitting an HTML form from a JSP page

Encountering the same origin policy issue with Ajax, but in need of sending a form post to a different server. The question at hand is: How can I call my JSP to automatically submit a form to another server? Attempts to use an AJAX call to the JSP page h ...

Extracting the color of a text layer with PSD.JS

Currently, I am utilizing PSD.JS (an efficient photoshop PSD file parser designed for both NodeJS and browsers) to decode several PSD files. Upon extraction of information from a text layer by the parser, color data is returned in the form of an array. Fo ...

Ensuring the Jquery Datepicker restricts selecting dates later than or equal to the start date (

I have a specific requirement where I need to implement two date pickers for entering "From" and "To" dates. The "ToDate" selected should be greater than or equal to the "FromDate" (after selecting a from date, all previous dates should be disabled in the ...

Do closures truly behave like objects, or are they something else entirely? (It appears not)

Let me clarify right off the bat that I am not inquiring about how closures function, as I already have a grasp on that concept. What I am curious about is what data type should be assigned to closures. Essentially, a closure can be thought of as a record ...

Utilize Mongoose to filter data at the database level by providing the options in JSON format

I am currently working on implementing a filter for an array of objects containing product objects. My goal is to filter the data based on the product name in either ascending or descending order. I have written some code for this, but unfortunately, it is ...