2017-08-20 50 views
2

我有一個函數primeFactors我試圖找到所有的數字是某個n數字的除數,但同時它們也必須是素數。從某種意義上來說,只是一個基本的算法每次播放音頻聲音元素被推入陣列

雖然這樣做,我也認爲這將是有趣的(只是爲了它)放置音頻聲音播放每次語句循環通過塊。但是,聲音只播放一次,即使有時結果是由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; 
} 
+0

您是否想等待它在第二次播放前完成播放? – SLaks

+0

@SLaks是的,那會很好。 – IsaaK08

回答

3

您可以使用一個隊列。聲音只能播放一個,因爲在這個循環中它幾乎是瞬間的。此作品:

<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>