The timing calculations in Vue.js do not align with the standard JavaScript version

I am currently working on developing a 'beats per minute' (BPM) calculator, which is similar to the one available here. However, I have noticed that when using the BPM calculator from that link for testing on a particular song, it quickly approximates the actual value of 85.94 within just 7 keypresses and becomes even more accurate with further taps, eventually reaching within 0.05 of the true BPM. On the other hand, my Vue.js version, which is essentially coded in the same way, initially starts much higher (182 --> 126 --> 110) and gradually decreases. Even after 60 keypresses, it still remains off by approximately 2 BPM, and at the end of the song, it's about 0.37 BPM off.

Here is the code snippet for the plain-JavaScript version mentioned above:

var count = 0;
var msecsFirst = 0;
var msecsPrevious = 0;

function ResetCount()
{
count = 0;
document.TAP_DISPLAY.T_AVG.value = "";
document.TAP_DISPLAY.T_TAP.value = "";
document.TAP_DISPLAY.T_RESET.blur();
}

function TapForBPM(e)
{
document.TAP_DISPLAY.T_WAIT.blur();
timeSeconds = new Date;
msecs = timeSeconds.getTime();
if ((msecs - msecsPrevious) > 1000 * document.TAP_DISPLAY.T_WAIT.value)
{
count = 0;
}

if (count == 0)
{
document.TAP_DISPLAY.T_AVG.value = "First Beat";
document.TAP_DISPLAY.T_TAP.value = "First Beat";
msecsFirst = msecs;
count = 1;
}
else
{
bpmAvg = 60000 * count / (msecs - msecsFirst);
document.TAP_DISPLAY.T_AVG.value = Math.round(bpmAvg * 100) / 100;
document.TAP_DISPLAY.T_WHOLE.value = Math.round(bpmAvg);
count++;
document.TAP_DISPLAY.T_TAP.value = count;
}
msecsPrevious = msecs;
return true;
}
document.onkeypress = TapForBPM;

//  End -->

Below is my own implementation:

computed: {
tappedOutBpm: function() {
let totalElapsedSeconds = (this.timeOfLastBpmKeypress - this.timeOfFirstBpmKeypress) / 1000.0;
let bpm = (this.numberOfTapsForBpm / totalElapsedSeconds) * 60.0;
return Math.round(100*bpm)/100;
},
},
methods: {
tapForBPM: function() {
let now = new Date;
now = now.getTime();
// let now = window.performance.now()
if (this.timeOfFirstBpmKeypress === 0 || now - this.timeOfLastBpmKeypress > 5000) {
this.timeOfFirstBpmKeypress = now;
this.timeOfLastBpmKeypress = now;
this.numberOfTapsForBpm = 1;
} else {
this.timeOfLastBpmKeypress = now;
this.numberOfTapsForBpm++;
}
}
}

Answer №1

After analyzing both of our code snippets, I was able to pinpoint the issue.

The root cause was my premature assumption that each tap by the user equated to a single event. However, upon closer inspection, I realized that what I truly needed to track were not just taps, but beats - and the first beat actually required two taps: the initial one and the final one. Therefore, I made the decision to refactor the variable name to numberOfTappedOutBeats and reset it to 0 after the first tap instead of setting it to 1.

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

Challenges with Cross-Origin Resource Sharing (CORS) when accessing Uber API OAuth

I am encountering an issue while attempting to make client-side JS calls to Uber API endpoints that require the OAuth Bearer token, such as /v1/me. The problem arises due to the absence of the Access-Control-Allow-Origin header in the response. I have suc ...

What are some strategies for retrying an Apollo Client query after a failure?

When working with Next.js server-side rendering (SSR), I often encounter a query failure on the first try due to the backend not being fully ready. In such cases, I would like to retry the fetch using ApolloClient. const PREVIEW = { query: MY_PREVIEW_ ...

capture the element with the specified #hash using Jquery

Illustration: Assuming I visit google.com/#search function checkHash(){ if(window.location.hash != hash) { $("elementhashed").animate( { backgroundColor: "#ff4500" }, 1 ).animate( { backgroundColor: "FFF" }, 1500 ); hash = window.location.hash; } t=se ...

Displaying information on an Angular user interface grid

I am facing an issue with displaying data in a UI grid table. I have set up an API through which I can access the data in my browser, but I am encountering difficulties when it comes to rendering the data. Below is my Angular controller where I have defin ...

Why is it that this particular line of code sometimes gives me an "undefined" result before returning an actual value?

Why does the method 'equal' always return with an "undefined" followed by a number? And when I try to parse it, it returns me a NaN. <!DOCTYPE> <html> <head> <script> var fnum = 0; var secondNum; var operation; functi ...

Using JQuery to monitor the loading of a newly selected image src attribute

As a newcomer to JavaScript and JQuery, I am facing a challenge that I couldn't find a solution for in other discussions: I have a function that retrieves the path to an image (/API/currentImage) using a GET request and needs to update the src attrib ...

Using Node.js and Hapi.js alongside Angular.js for web development

Could someone please help me understand how to integrate nodejs (hapi server) with AngularJs? I initially thought that I could intercept all requests made to my Hapi server and handle them using angularjs routes / REST, but it seems like I'm encounter ...

Issues with JavaScript Content Loading in epub.js on a Website

Hey there, I'm currently experimenting with the epub.js library and trying to set up the basics. However, I'm encountering an issue where the ebook is not showing up in my browser: <!DOCTYPE html> <html lang="en"> <head&g ...

Creating a Standard DIV Element (JavaScript Code)

Just a quick question here. http://jsfiddle.net/fkling/TpF24/ In this given example, I am looking to have < div>Bar 1</div> open as default... Any suggestions on achieving that? That would be all for now. Thank you so much! :D The JS script: var ...

What is the best way to deactivate buttons with AngularJS?

I have a situation where I need to disable the save button in one function and permanently disable both the save as draft and save buttons in another function using AngularJS. How can I accomplish this task with the disable functionality in AngularJS? Her ...

Set up your Typescript project to transpile code from ES6 to ES5 by utilizing Bable

Embarking on a new project, I am eager to implement the Async and Await capabilities recently introduced for TypeScript. Unfortunately, these features are currently only compatible with ES6. Is there a way to configure Visual Studio (2015 Update 1) to co ...

When using AngularJS, the templateUrl feature delays the initialization of the controller, causing issues with dependent code

Recently, I began experimenting with AngularJS and so far, everything seems to be going smoothly except for one small issue. Let's consider a scenario where I have two directives, with one directive relying on the other, like this: angular.module(&ap ...

Creating a precise regular expression for route length in Express JS

Currently, I am facing an issue while setting a route in my application. I want the URL parameter to be exactly 2 characters long, but unfortunately, the following code snippet is not producing the desired result: app.all('/:lng{2}?',function (r ...

designing a modular socket.io framework in node.js

Suppose in a node.js application, we have an app.js file structured like this: var express = require('express') var app = express(); var server = http.createServer(app); ... module.exports = { app:app, server:server } Additionally, there ...

The local authentication feature in NodeJS Passport is experiencing issues and not functioning properly

I have integrated passportjs local for authentication. However, I am facing an issue where it always redirects to the failureRedirect without displaying any error messages. The redirect also includes the original username and password, resulting in a dupli ...

Is it possible to create a sticky element that stays fixed to the window without using JavaScript?

Using position: sticky has been a game-changer for me. It resolves many issues without the need for JavaScript. However, I've encountered a roadblock. I am trying to create a sticky element that is nested inside multiple <div> elements. Since po ...

The callback function in AngularJS filters

I'm currently using an AngularJS filter to sort through a list of items. Here is the Jade markup I am using: li(ng-repeat="parcel in parcels | filter : filterActiveAreaParcels") After the filter function runs and the elements are displayed in the DO ...

Efficient State Management with React-Redux for Streamlined HTTP Requests

In the process of developing a React-Redux application, I have encountered a situation where I need to display a cancel button while a specific HTTP request is ongoing. Upon successful execution of the request, the UI should display the results. If the use ...

There was an error in React-Native using Native-base, as a failed prop type with an Invalid props.style key "NativeBase" was supplied to the "View"

Software Versions: React: 16.3.1 React-Native: ~0.55.2 Native-Base: ^2.8.0 Problem Alert: Warning: Failed prop type: Invalid props.style key 'NativeBase' supplied to 'View' Operating Systems: This warning keeps popping up in my r ...

Angular2 bootstrapping of multiple components

My query pertains to the following issue raised on Stack Overflow: Error when bootstrapping multiple angular2 modules In my index.html, I have included the code snippet below: <app-header>Loading header...</app-header> <app-root>L ...