簡體   English   中英

無法弄清楚如何在 Javascript 中擴展 Beats Per Minute 計數器功能?

[英]Can't figure out how to expand Beats Per Minute counter functionality in Javascript?

我編寫了這段代碼,它讓用戶每次感覺到心跳時點擊鼠標按鈕。 然后它會計算第一次和最后一次點擊之間的時間,如果這個速度繼續下去,它會計算你的 BPM。

我想補充的是,它會將大約 10 個 BPM 數據(點擊次數)放入一個數組中,然后在點擊 10 次后,它將根據 10 個 BPM 數據計算您的平均心率,它會告訴您是否健康或不。 我知道這聽起來很簡單,但我是 javascript 新手,我發現通過制作如此小的應用程序來學習這門語言真的很棒,沒有比這更好的學習方法了!

如果有人能指出我正確的方向,那就太好了。

這是我到目前為止:

    lastTapSeconds = 0;
    bpm = 0;

    var tapDiv = document.getElementById("tapDiv");

    function bpmCounter() { 

        var tapSeconds = new Date().getTime();

        bpm = ((1 / ((tapSeconds - lastTapSeconds) / 1000)) * 60);
        lastTapSeconds = tapSeconds;            
        tapDiv.innerHTML = '<h1 style="display:inline;">' + 
                            Math.floor(bpm) + 
                           '</h1><img style="height:150px;width:150px;" src="img/heart.png"/>';  
    }

    tapDiv.onmousedown = bpmCounter;

因此,我修復了您代碼的某些部分,包括一種為您即時計算平均值的方法。

檢查這個小提琴,看看這是否是你要找的!

http://jsfiddle.net/q85awqsp/2/

主要是創建var beats = []然后使用beats.push(Math.floor(bpm))添加值;

完整的JS在這里:

var lastTapSeconds = 0;
var bpm = 0;
var beats = [];
var average = 0;
var count = 0;

var tapDiv = document.getElementById("tapDiv");

$(document).on('click', function() {
    var tapSeconds = new Date().getTime();

    bpm = ((1 / ((tapSeconds - lastTapSeconds) / 1000)) * 60);
    lastTapSeconds = tapSeconds;
    tapDiv.innerHTML = '<h1 style="display:inline;">' + Math.floor(bpm) + '</h1>';
    beats.push(Math.floor(bpm));
    average *= count;
    average += Math.floor(bpm);
    count++;
    average /= count;

    if(beats.length >= 10) {
        alert("Average " + average);
    }
});

使用 Rxjs Observables 很容易:

import { fromEvent } from 'rxjs'; 
import { bufferCount, map, pluck, timeInterval } from 'rxjs/operators';

const btn = document.getElementById("btn"); // get button
fromEvent(btn, 'click').pipe(
  timeInterval(), // get interval between clicks in ms
  pluck('interval'), // strips the inverval property
  bufferCount(10,1),  // buffers last 10 values and return a array of them
  map(arr => arr.reduce((a, b) => a + b, 0) / arr.length), // get avarage of the array
  map(ms => Math.round(60000 / ms)), // calculate bpm
).subscribe(bpm => console.log(bpm + ' bpm'));

使用 bufferCount 您需要單擊 10 次,直到結果顯示在控制台上。 如果您想在開始單擊時正確顯示 bpm,然后繼續獲取最后 10 個值的平均值,請將 bufferCount 行替換為:

.scan((acc, curr) => {
    acc.push(curr);

    if (acc.length > 10) {
        acc.shift();
    }
    return acc;
}, []),

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM