Utilizing elapsed time in coding to create a function for DOM manipulation

As a new software engineering student, I am facing a challenge that I am struggling to overcome. I am currently working on developing a basic rhythm game similar to Guitar Hero using HTML, CSS, and JavaScript.

I have successfully implemented an elapsedTime function that starts a timer as soon as the start button is pressed. However, I am now stuck on how to create a function that utilizes this elapsed time to drop notes based on integers/floats stored in an array. Essentially, I need to compare the numbers in the array to the current elapsed time and determine when it is the appropriate moment to drop a note. Any suggestions or explanations on how to tackle this issue would be highly appreciated. Thank you in advance!

 
let elapsedTime = 0;
let counter = 0;

function increaseCounter() {
  if (counter >= 10) {
    clearInterval(intervalId); // Stop the interval when the counter reaches 10
    console.log("Interval stopped.");
    return;
  } else {
    counter++;
    console.log(`The counter is ${counter}`);
  }
}

const intervalId = setInterval(increaseCounter, 428.571);

Answer №1

If you're looking to track time accurately in your web application, one option is to utilize requestAnimationFrame(). This method schedules a callback to be executed before the next repaint, providing the number of milliseconds since navigation started as an argument. Here's an example of how you could use it:

let start;
let previousTimeStamp;

function step(timeStamp) {
  if (start === undefined) {
    start = timeStamp;
  }
  const elapsed = timeStamp - start;
  // ... render something,
  // then schedule another frame:
  window.requestAnimationFrame(step);
}

window.requestAnimationFrame(step);

Another option is performance.now(), which provides time elapsed in milliseconds since navigation began with an accuracy limited to ~100 microseconds. To increase accuracy to ~5 microseconds, consider serving your page with specific headers:

Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp

For another alternative, document.timeline.currentTime gives you the elapsed time in milliseconds since the page was loaded. Keep in mind browser privacy settings may cause this value to differ by up to 100 milliseconds.

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

Import an array in Python from a text file formatted in ASCII style

Inside the file named "array.txt", there is a 5x5 array of two-digit numbers presented as follows: +-------------------------+ ¦ 34 ¦ 21 ¦ 32 ¦ 41 ¦ 25 ¦ +----+----+----+----+-----¦ ¦ 14 ¦ 42 ¦ 43 ¦ 14 ¦ 31 ¦ +----+----+----+----+-----¦ ¦ ...

Utilizing iOS Local Storage for Efficient Form Submission Handling

I feel like my brain is on the verge of exploding. I just can't seem to get this to work as intended, and I'm struggling to pinpoint the issue. Currently, I have a form that needs to be processed using AJAX. Before proceeding with that, I want ...

Error message: The protocol "https:" is not compatible with this function. Please use "http:" instead

I decided to use IBM Bluemix for my school project, where I am working on creating a web service. For my project, I need to fetch JSON data from an API in order to utilize the provided information. Currently, I am utilizing the http get method to retrieve ...

How can we ensure that Ajax consistently provides useful and positive outcomes?

Here is my PHP code: function MailList() { $this->Form['email'] = $_POST["email"]; $index = $this->mgr->getMailList($_POST["email"]); } // SQL code function getMailList($email) { $mailArray = Array(); $sql ...

What advantages come from destructuring in conjunction with require statements?

When utilizing require, is there a performance advantage or disadvantage to importing the entire module versus only importing selected functions? It's my understanding that when using require to import modules (as opposed to using import), compilers ...

Is the HTML5 type of button functioning properly, while the type of submit is not working as

Looking to validate a form before running a JavaScript function? Check out this code snippet: function updateMap() { //dummy } <form> <div class="group"> <input type="number" id="hour" min="0" max="23" required> <span cl ...

How can I use appendChild to place two different elements into a single div?

While exploring similar questions on this topic, I have unfortunately not come across a solution that works for me. My challenge is trying to insert two a elements inside of a newly created div element using appendChild. However, I am unable to append them ...

Is it possible to link multiple references to a single Element/Node?

I am working on a function component that needs to pass the incoming ref from the parent to a div it is rendering. Additionally, I want to create and assign a separate ref inside the component to the same div. However, due to an element only accepting one ...

Holding off on completing a task until the outcomes of two parallel API requests are received

Upon page load, I have two asynchronous API calls that need to be completed before I can calculate the percentage change of their returned values. To ensure both APIs have been called successfully and the total variables are populated, I am currently using ...

Activate just the show more / show less button on the website that has several buttons with identical ids

Whenever the "show more" button is clicked, additional images are displayed in the gallery and the button text changes to "show less". However, in my ExpressionEngine (CMS) templates and entries, all "show more" buttons share the same id, causing other but ...

Text displayed in dropdown when selecting autocomplete option from Material UI

I'm facing a problem with the Material UI's Autocomplete Component. The issue is that the value is being shown instead of the text element. My data source format looks like this: [{value: 'someValue', text: 'My Text'}, {value ...

Can you explain the syntax for the Javascript tag?

While browsing through some code, I stumbled upon this snippet and found myself puzzled by the not:. Is it a tag of some sort? And if so, are there alternative applications for it? var foo = { not: function(bool) { return !bool; } } I'm curious t ...

Retrieve JSON object based on its unique identifier from a different JSON file

I am working with 2 API resources: and it returns JSON data like this: { "id": 771, "title": "Call to Alyce Herman - Engine Assembler", "assigned_with_person_id": 317, } provides ...

Prevent ng-click functionality from activating when clicking on a link inside an external element

I am facing an issue on my website using ui-router. I have a table with ng-click set on the cells, but there are links inside the cells as well. My goal is to disable the ng-click when the link is clicked. <div ng-click="click()" style="background: #d3 ...

Encountering an ERROR with the message "Error: NG0100: ExpressionChangedAfterItHasBeenCheckedError" while attempting to apply a filter to

My mat table includes a filter that utilizes chips to sort by multiple criteria. Upon my initial attempt to filter and save the criteria, I encountered an error called ExpressionChangedAfterItHasBeenCheckedError. The error message indicates a transition f ...

What is the best way to implement client side validation for a related input field using JavaScript in a Rails application?

Struggling to find a solution for adding a validation check for a dropdown list that is dependent on another input selection in a different form. It seems like database validation may be necessary, but I'm unsure of the best approach. Any suggestions ...

Delete the span element if the password requirements are satisfied

I am implementing password rules using span elements. I aim to dynamically remove each span that displays a rule once the input conditions are met. Currently, I have succeeded in removing the span related to the minimum length requirement but I am unsure h ...

Top way to include an HTML and javascript file in an Ext.Panel within Sencha Touch

My main goal is to efficiently include external HTML files and display them on an Ext.Panel in Sencha touch 2.3 by creating a wrapper module for the HTML file that can be instantiated using xtype, with an external Javascript file for event handling. Updat ...

Instead of receiving the actual values from the array, I am seeing the memory addresses of the array elements (Output:[I@59494225) in Scala. In the following code snippet, I anticipate the output to be (2

Here, the task is to compare the elements of arrays a(i) and b(i), updating the scores accordingly. If a[i] is greater than b[i], a is given 1 point. If b[i] is greater than a[i], b is awarded 1 point. object MyWizard extends App { def compar ...

What is the best way to delay JavaScript execution until after React has finished rendering?

Perhaps this is not the exact question you were expecting, but it did catch your attention :) The issue at hand revolves around the fact that most of the translations in my text do not update when the global language changes. Specifically, the translation ...