每次将元素推入数组时播放音频

Playing audio sound everytime an element is pushed in array

我有一个名为 primeFactors 的函数,我试图在其中找到作为某个 n 数的除数的所有数字,但同时,它们也必须是质数。只是某种意义上的基本算法。

在这样做的同时,我还认为放置每次 while 语句循环通过块时播放的音频声音会很有趣(只是为了它)。然而,声音只播放一次,即使有时结果是 3 个因素的数组(例如 [2, 7, 11])。在这种情况下,我希望在将每个元素推入数组之前播放三遍声音。这是我的代码:

function primeFact(n) {
    let factors = [];
    let divisor = 2;
    let clap = new Audio('clap.mp3');

    while (n > 2) {
        if (n % divisor == 0) {
            clap.currentTime = 0;
            clap.play();
            factors.push(divisor);
            n = n / divisor;
        } else {
            divisor++;
        }
    }
    return factors;
}

您可以使用队列。声音只播放一个,因为在那个循环中它几乎是瞬间的。这有效:

<script>
var sounds = new Array,
    clap = new Audio('clap.mp3'); // no need to assign it every time
function primeFact(n) {
    let factors = [];
    let divisor = 2;

    while (n > 2) {
        if (n % divisor == 0) {
            clap.currentTime = 0;
            sounds.push(clap); // add sound to queue
            factors.push(divisor);
            n = n / divisor;
        } else {
            divisor++;
        }
    }
    playQueuedSounds(); // play all sounds added
    return factors;
}
function playQueuedSounds() {
    if (sounds.length === 0) return;
    var sound = sounds.pop(); // get last sound and remove it
    sound.play();
    sound.onended = function() { // go look at the queue again once current sound is finished
        playQueuedSounds();
    };
}
primeFact(25); // two clap noises :)
</script>