I know that this question has been asked before on this platform, but I am really unable to implement the same thing that this friend implemented *(I mean Roy's answer). How will I pause the timer, mean (clear interval) from an outside function? according to my algorithm the function checkAnswer (should) be out side of the fetchQuesiton() function, It's not a big problem if it was inside but it's better for me to be outside, Help as much as you can. [edit] more explain: let's imagine that a player is playing this game, so when the timer reaches to 0, and the player until now didn't choose any answer, it will then clear that timer and then move to the checkAnswer function, which will then check for no answer, this means (in the future, when I make it) that it (checkAnswer) will return false, mean the answer is incorrect. another case, is when the player chooses an answer, it will pauses that setInterval timer, and check for the answer if it was correct or incorrect.
function theCallerFunction() {
fetchQuesiton();
//this is just an overview from a code I am writing.
}
var fetchQuesiton = async() => {
//this function should be async because later it will check a value responded by a promise.
//start timer
let timer = 15;
const startTimer = setInterval(() => {
timer--;
console.log(timer);
if (timer == 0) {
clearInterval(startTimer);
console.log("TIMEUP! YOU'RE LOSER!");
checkAnswer();
}
}, 1000);
//[click] on chances
let options = document.querySelectorAll('.option');
options = Array.prototype.slice.call(options);
options.forEach(cur => {
cur.addEventListener('click', checkAnswer);
});
}
var checkAnswer = async() => {
//this function should be async because later it will check a value responded by a promise.
clearInterval(startTimer);
console.log("I am working!");
}
theCallerFunction();
<div class="option">a)</div>
<div class="option">b)</div>
<div class="option">c)</div>
<div class="option">d)</div>