Javascript 为什么我的循环不能工作?
我一直在尝试循环一个函数,但我似乎无法使它按我所希望的那样工作。下面是我的循环Javascript 为什么我的循环不能工作?,javascript,code-snippets,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'); 这是我的职责 functio
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,它也不会循环。你们能帮我弄清楚如何循环myfunction吗?谢谢您可以使用基于时间间隔的解决方案,而不是使用类似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;
}
}
由于
myFunction
是异步的,因此返回的myFunction
函数undefined
不是回调返回的值为什么需要setTimeout()
?正如@Arun所说,它使myFunction
async,循环中的语句a=myFunction(a)
不再等待myFunction
的返回值。