在没有事件触发器的情况下重用(迭代)代码

时间:2016-01-09 17:35:42

标签: javascript

任何人都可以解释为posible(由于时间不足而学习js非常慢)如何迭代同一段代码。我需要在短暂延迟后一次又一次地重放声音,使用Math.Random而不使用事件触发器。

var birdsSing = Math.floor((Math.random() * 10) + 1); 
    if ( birdsSing === 1){
        birds.play();
    }

2 个答案:

答案 0 :(得分:2)

使用setInterval()功能:

// Milliseconds between sound playbacks
// Change this value to how often you want the sound to play
var playbackInterval = 500;

setInterval(function() {
    var birdsSing = Math.floor((Math.random() * 10) + 1); 
    if (birdsSing === 1) { birds.play(); }
}, playbackInterval);

答案 1 :(得分:0)

您需要使用setInterval();

请参阅: JavaScript timers (Mozilla Developer Network)