0

我正在使用以下代码(其中包含一些 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;
        }
    }
} );

提前致谢,

4

3 回答 3

1

你可以做这样的事情:

function doforsec(msec, func) {
    var curDate = new Date().getTime();
    while ((new Date().getTime() - curDate) < msec) {
        func();
    }
}
doforsec(200, function() {
    console.log(new Date().getSeconds())
});​

这会一次又一次地执行给 doforsec 的函数,直到指定的时间段(以毫秒为单位)结束。(首先我有几秒钟,但我认为毫秒会更好)

JSfiddle

于 2012-07-19T14:20:29.660 回答
0

因为我的截止日期是......好吧,大约 8 小时后发布这个......我决定重新编写脚本并使用 jQuery 插件:

Array.prototype.remove = function(from, to) {
    var rest = this.slice((to || from) + 1 || this.length);
    this.length = from < 0 ? this.length + from : from;
    return this.push.apply(this, rest);
};

$(document).ready(function(){

        var staff = [ 'hardcoded', 'list', 'of', 'staff', 'members' ];

        $('button#start').click( function() {
        var $display = $('#display'),
            $results = $('#results table');
        $display.removeClass( "winner" );
        $display.addClass( "spinner" );

        var counter = 0,            
            rand = 0,
            run_time = 10,
            delay = ( run_time * 100 ) / staff.length,
            loop_number = 5,
            max_count = staff.length * loop_number;

        $display.doTimeout( 'loop', delay, function() {
            counter++;
            var newRand = Math.floor( Math.random() * staff.length );
            if ( rand === newRand ) {
                rand = Math.floor( Math.random() * staff.length );
            } else {
                rand = newRand;
            }

            $(this).text( staff[rand] );

            if ( counter < max_count ) { return true; }
            else {
                $('#results tr:last').after('<tr><td class="number">' + staff.length + '</td><td>' + staff[rand] + '</td></tr>');
                staff.remove( rand );
            }
        });

        $display.doTimeout( 'class', max_count * delay, function() {
            $display.removeClass( "spinner" );
            $display.addClass( "winner" );
        });
    });

});
于 2012-07-19T23:28:18.410 回答
0

在 var timeout = ( 15000 / total ) 之后;插入以下内容,并删除 (i=0; i

var totalTime = 2000;
var timeOut= Math.Ceiling(totalTime/timeout);
var timesToDisplay = totalTime / timeOut;
var currentDisplay = 0;
for (currentDisplay = 0; currentDisplay < timesToDisplay; currentDisplay++) {

    i = currentDisplay % total;
于 2012-07-19T14:09:06.453 回答