我正在使用以下代码(其中包含一些 Frog VLE API 代码;希望这不太相关)从列表中选择一个随机学生。
这很好用,但有时——考虑到它的随机性——它只运行很短的一段时间。是否可以先循环多次,以确保它至少运行 X 段时间?
var Count = 0;
/* construct the array of people */
for (var i in data.users) {
for (var n = 0; n < data.users[i].Quantity; n++) {
var TempObj = { 'Count' : Count, 'Student_ID' : i, 'Student_Name' : data.users[i].Student_Name };
RewardPurchases.PurchasesArray[Count] = TempObj;
Count++;
}
}
...这里有更多代码,与脚本的工作方式无关...
$('button#random').click( function() {
/* first things first, play a drum-roll when the button is clicked! */
$('embed').remove();
$('body').append('<embed src="/user/74/177499.wav" autostart="true" hidden="true" loop="true">');
/* take the RewardPurchases.PurchasesArray and sort it so that there's no particular order */
RewardPurchases.PurchasesArray.sort(function() {return 0.5 - Math.random()})
/* remove the winner class for consecutive re-rolls */
$display.removeClass( "winner" );
$display.addClass( "spinner" );
/* determine the number of people in the array and calculate a random winner */
var total = RewardPurchases.PurchasesArray.length,
selected = Math.floor( Math.random() * total ),
i = 0;
/* work out how long each name should appear for, dependent upon how many people are in the array */
var timeout = ( 15000 / total );
/* run through the array of people ... */
for (i=0; i<total; i++) {
setTimeout((function(i){
return function(){
console.log( "timeout", i );
/* ... if the person in the array is a valid person! then display their name */
if (typeof RewardPurchases.PurchasesArray[i] === 'object' && typeof RewardPurchases.PurchasesArray[i] !== null) {
$display.text( "[" + RewardPurchases.PurchasesArray[i].Count + "] " + RewardPurchases.PurchasesArray[i].Student_Name.toUpperCase() );
/* if we encounter the winner, play a cheering wav and change the class of the display so that they appear in big, bold, red text */
if( i === selected ) {
$('embed').remove();
$('body').append('<embed src="/user/74/177086.wav" autostart="true" hidden="true" loop="false">');
$display.addClass( "winner" );
}
}
};
}(i)), i*timeout);
/* if the winner has been found, break the loop */
if( i === selected ) {
break;
}
}
} );
提前致谢,