【问题标题】:Limit number of calls some function in JS限制JS中某些函数的调用次数
【发布时间】:2015-06-30 16:26:17
【问题描述】:

好的,我有一个在循环模式下运行的小脚本。是用来赌的。这是想法: 我无限次翻转硬币(循环),双方都有 50/50 的机会。但是,在某些时候,我会在“数字侧”行中获得 5 次:...,head, number,head, NUMBER, NUMBER, NUMBER, NUMBER, NUMBER,... 如果在“数字侧”行中获得 5 次,我需要限制脚本调用函数。 就我而言,我有函数 multiply() 并且有时会调用该函数。因此,我需要限制调用 multiply() 函数的次数,例如。 5 或 4.. 所以,如果脚本连续调用函数 multiply() 5 次,它会做一些事情(例如,显示警报或其他事情)。 这是脚本:

var startValue = '0.00000001', // Don't lower the decimal point more than 4x of current balance
            stopPercentage = 0.001, // In %. I wouldn't recommend going past 0.08
            maxWait = 500, // In milliseconds
            stopped = false,
            stopBefore = 3; // In minutes
     
    var $loButton = $('#double_your_btc_bet_lo_button'),
                    $hiButton = $('#double_your_btc_bet_hi_button');
     
    function multiply(){
            var current = $('#double_your_btc_stake').val();
            var multiply = (current * 2).toFixed(8);
            $('#double_your_btc_stake').val(multiply);
    }
     
    function getRandomWait(){
            var wait = Math.floor(Math.random() * maxWait ) + 100;
     
            console.log('Waiting for ' + wait + 'ms before next bet.');
     
            return wait ;
    }
     
    function startGame(){
            console.log('Game started!');
            reset();
            $loButton.trigger('click');
    }
     
    function stopGame(){
            console.log('Game will stop soon! Let me finish.');
            stopped = true;
    }
     
    function reset(){
            $('#double_your_btc_stake').val(startValue);
    }
     
    // quick and dirty hack if you have very little bitcoins like 0.0000001
    function deexponentize(number){
            return number * 1000000;
    }
     
    function iHaveEnoughMoni(){
            var balance = deexponentize(parseFloat($('#balance').text()));
            var current = deexponentize($('#double_your_btc_stake').val());
     
            return ((balance*2)/100) * (current*2) > stopPercentage/100;
    }
     
    function stopBeforeRedirect(){
            var minutes = parseInt($('title').text());
     
            if( minutes < stopBefore )
            {
                    console.log('Approaching redirect! Stop the game so we don\'t get redirected while loosing.');
                    stopGame();
     
                    return true;
            }
     
            return false;
    }
     
    // Unbind old shit
    $('#double_your_btc_bet_lose').unbind();
    $('#double_your_btc_bet_win').unbind();
     
    // Loser
    $('#double_your_btc_bet_lose').bind("DOMSubtreeModified",function(event){
            if( $(event.currentTarget).is(':contains("lose")') )
            {
                    console.log('You LOST! Multiplying your bet and betting again.');
                   
                    multiply();
     
                    setTimeout(function(){
                            $loButton.trigger('click');
                    }, getRandomWait());
     
                    //$loButton.trigger('click');
            }
    });
     
    // Winner
    $('#double_your_btc_bet_win').bind("DOMSubtreeModified",function(event){
            if( $(event.currentTarget).is(':contains("win")') )
            {
                    if( stopBeforeRedirect() )
                    {
                            return;
                    }
     
                    if( iHaveEnoughMoni() )
                    {
                            console.log('You WON! But don\'t be greedy. Restarting!');
     
                            reset();
     
                            if( stopped )
                            {
                                    stopped = false;
                                    return false;
                            }
                    }
                    else
                    {
                            console.log('You WON! Betting again');
                    }
     
                    setTimeout(function(){
                            $loButton.trigger('click');
                    }, getRandomWait());
            }
    });

如果连续“输”5 次,我需要这个来停止越来越多的失分,因为如果输了,脚本总是乘以 2。而且剧本输了一定要倍增,这是赌博的规则:)

【问题讨论】:

标签: javascript function loops


【解决方案1】:

创建全局变量:

var startValue = '0.00000001', // Don't lower the decimal point more than 4x of current balance
            stopPercentage = 0.001, // In %. I wouldn't recommend going past 0.08
            maxWait = 500, // In milliseconds
            stopped = false,
            stopBefore = 3, // In minutes
            multiplyCalls = 0; // <--- Added this global

添加到变量和如果测试值

 function multiply(){
            if(multiplyCalls <= 5){ // test multiply
                var current = $('#double_your_btc_stake').val();
                var multiply = (current * 2).toFixed(8);
                $('#double_your_btc_stake').val(multiply);
                multiplyCalls++; // increment
            }else{
                console.log('you lost');
            }
    }

在游戏重置时重置您的变量

function reset(){
    $('#double_your_btc_stake').val(startValue);
    multiplyCalls = 0; // reset value
}

【讨论】:

    【解决方案2】:

    好的,我找到了解决办法:

    var startValue = '0.00000001', // Don't lower the decimal point more than 4x of current balance
            stopPercentage = 0.001, // In %. I wouldn't recommend going past 0.08
            maxWait = 500, // In milliseconds
            stopped = false,
            stopBefore = 3; // In minutes
            multiplyCalls = 0; // <--- Added this global
    
    var $loButton = $('#double_your_btc_bet_lo_button'),
                    $hiButton = $('#double_your_btc_bet_hi_button');
    
    
    function multiply(){
            if(multiplyCalls < 4){ // test multiply
                var current = $('#double_your_btc_stake').val();
                var multiply = (current * 2).toFixed(8);
                $('#double_your_btc_stake').val(multiply);
                multiplyCalls++; // increment
            }else{
                reset();
                console.log('=== RESETING ===');
            }
    }
    
    function getRandomWait(){
            var wait = Math.floor(Math.random() * maxWait ) + 100;
    
            console.log('Waiting for ' + wait + 'ms before next bet.');
    
            return wait ;
    }
    
    function startGame(){
            console.log('Game started!');
            reset();
            $loButton.trigger('click');
    }
    
    function stopGame(){
            console.log('Game will stop soon! Let me finish.');
            stopped = true;
    }
    
    function reset(){
            $('#double_your_btc_stake').val(startValue);
    
    }
    
    // quick and dirty hack if you have very little bitcoins like 0.0000001
    function deexponentize(number){
            return number * 1000000;
    }
    
    function iHaveEnoughMoni(){
            var balance = deexponentize(parseFloat($('#balance').text()));
            var current = deexponentize($('#double_your_btc_stake').val());
    
            return ((balance*2)/100) * (current*2) > stopPercentage/100;
    }
    
    function stopBeforeRedirect(){
            var minutes = parseInt($('title').text());
    
            if( minutes < stopBefore )
            {
                    console.log('Approaching redirect! Stop the game so we don\'t get redirected while loosing.');
                    stopGame();
    
                    return true;
            }
    
            return false;
    }
    
    // Unbind old shit
    $('#double_your_btc_bet_lose').unbind();
    $('#double_your_btc_bet_win').unbind();
    
    // Loser
    $('#double_your_btc_bet_lose').bind("DOMSubtreeModified",function(event){
            if( $(event.currentTarget).is(':contains("lose")') )
            {
                    console.log('You LOST! Multiplying your bet and betting again.');
    
                    multiply();
    
                    setTimeout(function(){
                            $loButton.trigger('click');
                    }, getRandomWait());
    
                    //$loButton.trigger('click');
            }
    });
    
    // Winner
    $('#double_your_btc_bet_win').bind("DOMSubtreeModified",function(event){
            if( $(event.currentTarget).is(':contains("win")') )
            {
                    if( stopBeforeRedirect() )
                    {
                            return;
                    }
    
                    if( iHaveEnoughMoni() )
                    {
                            console.log('You WON! But don\'t be greedy. Restarting!');
    
                            reset();
    
                            if( stopped )
                            {
                                    stopped = false;
                                    return false;
                            }
                    }
                    else
                    {
                            console.log('You WON! Betting again');
                    }
    
                    setTimeout(function(){
                            $loButton.trigger('click');
                    }, getRandomWait());
                    multiplyCalls = 0; // reset value
            }
    });
    

    谢谢@patrick 墨菲

    所以,我在“输”部分增加计数器并在“赢”部分重置计数器。谢谢大家:)

    【讨论】:

    • 这看起来很棒,很高兴你成功了!祝你项目的其余部分好运。
    【解决方案3】:

    你不能为函数调用计数创建一个全局变量并在每次执行函数时递增它吗?再加上在函数中添加一些条件,当你达到限制时会发生什么。

    【讨论】:

    • 将“global”替换为“scoped”,这就是完成它的方法。
    【解决方案4】:

    您可以像这样模拟 c 样式的块作用域静态变量:

    function foobar() {
        this._callCount = this._callCount || 0; // static scoped variable
        if (this._callCount++ >= 5) {
            // reached over 5, exitting.
            return;
        }
        // do something else
    }
    

    工作 jsfiddle 示例: http://jsfiddle.net/z5ojxjke/

    【讨论】:

    • 这是一个干净的解决方案,很好地将变量包含在函数中。
    • 它不包含在函数“内”。它是 this 所指的任何对象的属性。那可能是函数本身,也可能是完全不同的东西。 github.com/getify/You-Dont-Know-JS/blob/master/…
    • 是的,我明白,这只是意味着我喜欢代码保留在 foobar() 块中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多