Answer the question
In order to leave comments, you need to log in
How to return value from setTimeout inside setInterval?
export function fight(firstFighter, secondFighter) {
// Обьявление переменных
let promise = new Promise(function(resolve, reject){
let intervalId = setInterval(winner = function(){
let timeout1 = setTimeout(function () {
damage = getDamage(firstFighter, secondFighter);
if (damage > 0) {
console.log(secondFighterHealth + "-" + damage);
secondFighterHealth -= damage;
} else {
console.log('Второй блокировал удар первого!');
}
if (secondFighterHealth <= 0) {
window.winner = firstFighter;
clearInterval(intervalId);
resolve(winner);
clearTimeout(timeout2);
}
console.log('Second Health: ' + secondFighterHealth);
console.log('PAUSE!');
}, 250);
let timeout2 = setTimeout(function(){
damage = getDamage(secondFighter, firstFighter);
if (damage > 0) {
console.log(firstFighterHealth + "-" + damage);
firstFighterHealth -= damage;
} else {
console.log('Первый блокировал удар второго!');
}
if (firstFighterHealth <= 0) {
window.winner = secondFighter;
clearInterval(intervalId);
resolve(winner);
clearTimeout(timeout1);
}
console.log('First Health: ' + firstFighterHealth);
console.log('PAUSE!');
}, 500);
}, 750);
});
promise.then(function(){
console.log(window.winner.name);
});
}
const winner = fight(...selectedFighters.values());
showWinnerModal(winner);
Answer the question
In order to leave comments, you need to log in
Obviously, wrap setInterval in a promise and throw the result in resolve
. At the same time, in your code, you need to clean not only clearInterval but also clearTimeout, even if the second player dies too, you won’t track this with a promise, resolve is executed only once. Therefore, if one player died, there is no point in waiting for the second setTimeout to complete, I don’t see any point in spreading it into different setTimeouts if the first one always beats first
. I just didn’t understand why to duplicate the question by slightly changing the code.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question