有没有办法调整这个名称生成循环运行最少的秒数?

时间:2012-07-19 13:59:57

标签: javascript jquery

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

提前致谢,

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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;

答案 2 :(得分: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" );
        });
    });

});