为什么我的循环不起作用?

时间:2015-06-10 00:49:32

标签: javascript code-snippets

我一直试图循环一个函数,但我似乎无法让它按照我想要的方式工作。下面是我的循环

console.log('START LOOP MY FUNCTION');
a=1;
do{
    console.log('CALL MY FUNCTION');
    a=myFunction(a);
    console.log('EXIT MY FUNCTION');
}while(a==1);
console.log('EXIT LOOP MY FUNCTION');

这是我的功能

function myFunction(b) {
    setTimeout(function(){
        console.log('Start of My function');
        console.log('Inside b is '+b);
        var results = $('#dice > div.game > div > div.bet-history > table > tbody > tr');
        var result = $(results[0]).children('.dice-profit').children().text();
            console.log('BEFORE IF');
            if(result.substring(1) != $(betField).val()){
                console.log('################ERROR FOUND - Result:'+result.substring(1)+' Bet:'+$(betField).val()+' NOT EQUAL');
                console.log('AFTER IF');
                return b=1;
            }else{
                console.log('NO EROR YOU MAY NOW EXIT LOOP');
                console.log('AFTER ELSE');
                return b=0;
            }
        }, 3000);
    }

这是控制台中的输出

new:232 START LOOP MY FUNCTION
new:235 CALL MY FUNCTION
new:237 EXIT MY FUNCTION
new:239 EXIT LOOP MY FUNCTION
new:38 Start of My function
new:39 Inside b is 1
new:42 BEFORE IF
new:48 NO EROR YOU MAY NOW EXIT LOOP
new:49 AFTER ELSE

我认为它应该可以工作但是从控制台输出的外观来看,它在调用myfunction之前已经退出循环,这意味着即使b = 1它也不会循环。你能帮助我弄清楚如何循环我的功能吗?感谢

1 个答案:

答案 0 :(得分:0)

您可以使用基于区间的解决方案,而不是像

那样使用while循环
console.log('START LOOP MY FUNCTION');
//start the function
loop(function () {
    //this callback will be called once `a` becomes 1
    console.log('EXIT LOOP MY FUNCTION');
})

function loop(callback) {
    var a = 1,
        timer;
    //to run myFunction every 3 seconds
    timer = setInterval(function () {
        console.log('CALL MY FUNCTION');
        a = myFunction(a);
        console.log('EXIT MY FUNCTION');

        //check if `a` is 1 if so terminate the calls
        if (a != 1) {
            clearInterval(timer);
            callback();
        }
    }, 3000);
}

//This function should not do any async ops, it should just check the condition and return the value
function myFunction(b) {
    console.log('Start of My function');
    console.log('Inside b is ' + b);
    var results = $('#dice > div.game > div > div.bet-history > table > tbody > tr');
    var result = $(results[0]).children('.dice-profit').children().text();
    console.log('BEFORE IF');
    if (result.substring(1) != $(betField).val()) {
        console.log('################ERROR FOUND - Result:' + result.substring(1) + ' Bet:' + $(betField).val() + ' NOT EQUAL');
        console.log('AFTER IF');
        return 1;
    } else {
        console.log('NO EROR YOU MAY NOW EXIT LOOP');
        console.log('AFTER ELSE');
        return 0;
    }
}