I am creating rock, paper, scissors game. And after the battle I want the result to be displaying on the screen for 5 seconds then start counting backwards from 5. Both functions should start one after another but I don't know how to do it. I tried different variations using setTimeout() but apparently I am missing something. I did my research before asking the question but couldn't find anything helpful.
JS:
let elements = [
"../img/scissors.png",
"../img/rock.png",
"../img/paper.png",
];
const startBtn = document.querySelector('.start')
const startImg = document.querySelector('.all-elements')
const rules = document.querySelector('.rules')
const phase1 = document.querySelector('.phase-1')
const phase2 = document.querySelector('.phase-2')
const imgs = document.querySelectorAll('.wrapper img')
const opponent = document.querySelector('.opponent-choise')
const result = document.querySelector('.result')
let clicked = false
let time = 5
startBtn.addEventListener('click', ()=>{
phase1.style.display = "none"
phase2.style.display = "block"
})
for(let i = 0; i < imgs.length; i++){
let me = imgs[i]
me.addEventListener('click', ()=>{
if(clicked == false){
clicked = true
chooseSign(me, imgs)
countDown()
}
})
}
function chooseSign(b, c){
c.forEach((a)=>{
a.style.display = "none"
})
b.style.display = "block"
b.style.cursor = "auto"
displayOpponent()
checkForWinner(b, opponent)
}
function displayOpponent(){
let random = Math.floor(Math.random() * 3)
opponent.style.display = "block"
opponent.src = elements[random]
}
function checkForWinner(me, opponent){
let meSrc = me.getAttribute('src')
let opponentSrc = opponent.getAttribute('src')
if(me.src == opponent.src){
let a = "Draw!"
showWinner(a)
} else if
(meSrc == elements[0] && opponentSrc == elements[2] ||
meSrc == elements[1] && opponentSrc == elements[0] ||
meSrc == elements[2] && opponentSrc == elements[1])
{
let a = "You win!"
showWinner(a)
} else {
let a = "You lose!"
showWinner(a)
}
}
function showWinner(a){
result.textContent = a
setTimeout('showWinner()', 5000)
}
function countDown(){
result.textContent = time
time--
if(time == -1){
return
}
setTimeout('countDown()', 1000)
result.textContent = time
}
In case someone is wondering I solved the problem. Here is the code for the ones who need the answer. Sorry if I haven't provided the answer in the most optimal way.
JS:
let elements = [
"../img/scissors.png",
"../img/rock.png",
"../img/paper.png",
];
const startBtn = document.querySelector('.start')
const exitBtn = document.querySelector('.exit')
const startImg = document.querySelector('.all-elements')
const rules = document.querySelector('.rules')
const phase1 = document.querySelector('.phase-1')
const phase2 = document.querySelector('.phase-2')
const imgs = document.querySelectorAll('.wrapper img')
const opponent = document.querySelector('.opponent-choise')
const result = document.querySelector('.result')
let clicked = false
let time = 4 //put one more second to start on time
let refreshedTime = time
let a
startBtn.addEventListener('click', ()=>{
phase1.style.display = "none"
phase2.style.display = "block"
result.textContent = "Choose a sign!"
})
exitBtn.addEventListener('click', ()=>{
if(clicked == false){
phase1.style.display = "block"
phase2.style.display = "none"
}
})
for(let i = 0; i < imgs.length; i++){
let me = imgs[i]
me.addEventListener('click', ()=>{
setTimeout(()=>{
if(clicked == false){
clicked = true
time = refreshedTime
chooseSign(me, imgs)
setTimeout(countDown, 2000)
}
}, 1000)
})
}
function chooseSign(b, c){
c.forEach((a)=>{
a.style.display = "none"
})
b.style.display = "block"
b.style.cursor = "auto"
displayOpponent()
checkForWinner(b, opponent)
}
function displayOpponent(){
let random = Math.floor(Math.random() * 3)
opponent.style.display = "block"
opponent.src = elements[random]
}
function checkForWinner(me, opponent){
let meSrc = me.getAttribute('src')
let opponentSrc = opponent.getAttribute('src')
if(me.src == opponent.src){
a = "Draw!"
result.style.color = "yellow"
} else if
(meSrc == elements[0] && opponentSrc == elements[2] ||
meSrc == elements[1] && opponentSrc == elements[0] ||
meSrc == elements[2] && opponentSrc == elements[1])
{
a = "You win!"
result.style.color = "green"
} else {
a = "You lose!"
result.style.color = "red"
}
showWinner(a)
}
function showWinner(a){
result.textContent = a
}
function countDown(){
result.style.color = "black"
time--
if(time == -1){
clicked = false
imgs.forEach((img)=>{
img.style.display = "block"
img.style.cursor = "pointer"
})
opponent.style.display = "none"
result.textContent = "Choose a sign!"
return
}
setTimeout('countDown()', 1000)
result.textContent = time
}
Javascript setTimeout() function is asynchronous in order not to freeze all the js code during the delayed time interval. As you have not provided a minimal reproducible example, I could only guess what you intended. Here is the modified code:
let elements = [
"../img/scissors.png",
"../img/rock.png",
"../img/paper.png",
];
const imgs = document.querySelectorAll('.wrapper img')
const startBtn = document.querySelector('.start')
const startImg = document.querySelector('.all-elements')
const rules = document.querySelector('.rules')
const phase1 = document.querySelector('.phase-1')
const phase2 = document.querySelector('.phase-2')
const opponent = document.querySelector('.opponent-choise')
const result = document.querySelector('.result')
let clicked = false
let time = 5
startBtn.addEventListener('click', ()=>{
phase1.style.display = "none"
phase2.style.display = "block"
})
for(let i = 0; i < imgs.length; i++){
let me = imgs[i]
me.addEventListener('click', ()=>{
if(clicked == false){
clicked = true
chooseSign(me, imgs)
}
})
}
function chooseSign(b, c){
c.forEach((a)=>{
a.style.display = "none"
})
b.style.display = "block"
b.style.cursor = "auto"
displayOpponent()
checkForWinner(b, opponent)
}
function displayOpponent(){
let random = Math.floor(Math.random() * 3)
opponent.style.display = "block"
opponent.src = elements[random]
}
function checkForWinner(me, opponent){
let meSrc = me.getAttribute('src')
let opponentSrc = opponent.getAttribute('src')
if(me.src == opponent.src){
let a = "Draw!"
showWinner(a)
} else if
(meSrc == elements[0] && opponentSrc == elements[2] ||
meSrc == elements[1] && opponentSrc == elements[0] ||
meSrc == elements[2] && opponentSrc == elements[1])
{
let a = "You win!"
setTimeout(showWinner(a), 5000);
} else {
let a = "You lose!"
setTimeout(showWinner(a), 5000);
}
}
function showWinner(a){
result.textContent = a;
setTimeout(countDown(), 5000);
}
function countDown(){
result.textContent = time
time--
if(time == -1){
return
}
result.textContent = time
}
Please provide a minimal reproducible example (i.e. include your relevant html/css) in case there are any further problems.
Related
So I'm still practicing and learning and I'm creating a number guessing game and I was planning on re-using a existing button to trigger the reset of the game however for some reason it will reset however upon doing so-- resetGame() will reset variables but not start the checkGuess() like it's suppose to and only continue to randomize the randomNumber when 'submit' button is clicked..
I'm assuming that this must be bad practice and figure I shouldn't do this but wanted to ask why this wasn't re-starting the game as it should... what am I missing?
let randomNumber = Math.floor(Math.random() * 10) + 1;
let guessField = document.getElementById('guessField');
let enterButton = document.getElementById('userSubmit');
let lastResult = document.querySelector('.lastResult');
let lowOrHigh = document.querySelector('.lowOrHigh');
let guesses = document.querySelector('.guesses');
let guessRemaining = 5;
enterButton.addEventListener('click', checkGuess);
// function log() {
// console.log(Number(document.getElementById('guessField').value));
// }
function checkGuess() {
let userGuess = Number(guessField.value);
if (guessRemaining === 5) {
guesses.textContent = 'Previous guesses: ';
}
guesses.textContent += userGuess + ' ';
if (userGuess === randomNumber) {
lastResult.textContent = 'Congratulations! You got it right!';
lastResult.style.background = 'green';
gameOver();
} else if (guessRemaining < 1) {
lastResult.textContent = 'GAME OVER!';
gameOver();
} else {
lastResult.textContent = 'Wrong answer!';
lastResult.style.background = 'red';
lastResult.style.color = 'white';
if (userGuess < randomNumber) {
lowOrHigh.textContent = 'Too low!';
} else if (userGuess > randomNumber) {
lowOrHigh.textContent = 'Too high!';
}
}
guessRemaining--;
guessField.value = '';
guessField.focus();
}
function gameOver() {
guessField.disabled = true;
enterButton.setAttribute('value', 'Replay');
enterButton.addEventListener('click', resetGame);
}
function resetGame() {
randomNumber = Math.floor(Math.random() * 10) + 1;
// document.getElementById('userGuess').value = '';
lastResult.textContent = '';
guesses.textContent = '';
lowOrHigh.textContent = '';
guessField.disabled = false;
enterButton.setAttribute('value', 'Submit');
guessRemaining = 5;
}
The problem is that after you finish the game the resetGame callback is added as event listener and is triggered every time you click the userSubmit button. There are few possibilities how to solve this problem:
1. Check if the game is running
In this solution, you don't add the resetGame callback, but you call it within the checkGuess callback. To make this solution work you have to add a variable which represents if the game is running or not. This way if the game is still running the checkGuess callback will call the default behaviour, but after the gameOver is called, checkGuess will reset the game.
let randomNumber = Math.floor(Math.random() * 10) + 1;
let guessField = document.getElementById('guessField');
let enterButton = document.getElementById('userSubmit');
let lastResult = document.querySelector('.lastResult');
let lowOrHigh = document.querySelector('.lowOrHigh');
let guesses = document.querySelector('.guesses');
let guessRemaining = 5;
let isRunning = true;
enterButton.addEventListener('click', checkGuess);
function checkGuess() {
if (isRunning) { // Check if the game is running
let userGuess = Number(guessField.value);
if (guessRemaining === 5) {
guesses.textContent = 'Previous guesses: ';
}
guesses.textContent += userGuess + ' ';
if (userGuess === randomNumber) {
lastResult.textContent = 'Congratulations! You got it right!';
lastResult.style.background = 'green';
gameOver();
} else if (guessRemaining < 1) {
lastResult.textContent = 'GAME OVER!';
gameOver();
} else {
lastResult.textContent = 'Wrong answer!';
lastResult.style.background = 'red';
lastResult.style.color = 'white';
if (userGuess < randomNumber) {
lowOrHigh.textContent = 'Too low!';
} else if (userGuess > randomNumber) {
lowOrHigh.textContent = 'Too high!';
}
}
guessRemaining--;
guessField.value = '';
guessField.focus();
} else {
resetGame();
}
}
function gameOver() {
guessField.disabled = true;
enterButton.setAttribute('value', 'Replay');
isRunning = false;
// enterButton.addEventListener('click', resetGame); Move this line to the beggining
}
function resetGame() {
randomNumber = Math.floor(Math.random() * 10) + 1;
lastResult.textContent = '';
guesses.textContent = '';
lowOrHigh.textContent = '';
guessField.disabled = false;
enterButton.setAttribute('value', 'Submit');
guessRemaining = 5;
isRunning = true;
}
2. Remove the resetGame callback after reseting
Here you just remove the resetGame callback after it is called. First you add the resetGame (just like you have it now) after the game is finished, but remove the checkGuess as well so it doesn't trigger your logic. Next you remove the resetGame and add the guessCheck callbacks after the resetGame is called (you can see two lines at the end of resetGame function).
let randomNumber = Math.floor(Math.random() * 10) + 1;
let guessField = document.getElementById('guessField');
let enterButton = document.getElementById('userSubmit');
let lastResult = document.querySelector('.lastResult');
let lowOrHigh = document.querySelector('.lowOrHigh');
let guesses = document.querySelector('.guesses');
let guessRemaining = 5;
enterButton.addEventListener('click', checkGuess);
function checkGuess() {
let userGuess = Number(guessField.value);
if (guessRemaining === 5) {
guesses.textContent = 'Previous guesses: ';
}
guesses.textContent += userGuess + ' ';
if (userGuess === randomNumber) {
lastResult.textContent = 'Congratulations! You got it right!';
lastResult.style.background = 'green';
gameOver();
} else if (guessRemaining < 1) {
lastResult.textContent = 'GAME OVER!';
gameOver();
} else {
lastResult.textContent = 'Wrong answer!';
lastResult.style.background = 'red';
lastResult.style.color = 'white';
if (userGuess < randomNumber) {
lowOrHigh.textContent = 'Too low!';
} else if (userGuess > randomNumber) {
lowOrHigh.textContent = 'Too high!';
}
}
guessRemaining--;
guessField.value = '';
guessField.focus();
}
function gameOver() {
guessField.disabled = true;
enterButton.setAttribute('value', 'Replay');
enterButton.removeEventListener('click', checkGuess); // Remove checkGuess and add resetGame
enterButton.addEventListener('click', resetGame);
}
function resetGame() {
randomNumber = Math.floor(Math.random() * 10) + 1;
lastResult.textContent = '';
guesses.textContent = '';
lowOrHigh.textContent = '';
guessField.disabled = false;
enterButton.setAttribute('value', 'Submit');
guessRemaining = 5;
enterButton.removeEventListener('click', resetGame); // Remove resetGame and add checkGuess
enterButton.addEventListener('click', checkGuess);
}
How about a slightly improved approach?
You define a boolean variable named gameIsOver. When the game is over, you set the value to true and when you reset, set the value to false.
Then you update your enterButton's click event listener. If game is over, you call the resetGame() function, else you call checkGuess function.
let gameIsOver = false; // keep track if the game is over, initially its false
enterButton.addEventListener("click", function (e) {
if (gameIsOver) {
resetGame();
} else {
checkGuess();
}
});
function gameOver() {
/* your existing code */
gameIsOver = true;
}
function resetGame() {
/* your existing code */
gameIsOver = false;
}
I built a trivia game and if you run out of time then the function score() I wrote runs grades your game. This function is also tied to the submit button. So the issue arises when you finish the quiz with time remaining; because once you submit your score if the time goes to zero before you click try again it doubles your score.
How can get around this issue; I'm open to fixing it in the timer function or writing another function to prevent it from grading twice.
side note the try again button can't reset the page per requirements so I have the start button begin the countdown() (timer).
So the function I need is to check if score has been run and if it has don't run it again ; then the count has to reset when you click the start button.
var button = document.getElementById("main-button")
var taButton = document.getElementById("ta-button")
var quizText = document.getElementById("quiz")
var correct = 0;
var incorrect = 0;
var notAnswered = 0;
var correctText = document.getElementById("correct-text")
var incorrectText = document.getElementById("incorrect-text")
var notAnsweredText = document.getElementById("notAnswered-text")
var timeLeft = 70;
var timeLeftText = document.getElementById("timeLeft-text")
var elem = document.getElementById('some_div');
var timerId = setInterval(countdown, 1000);
// timer function
function countdown() {
if (timeLeft == 0) {
clearTimeout(timerId);
score();
} else {
timeLeftText.textContent = "Time Remaining " + timeLeft;
timeLeft--;
}
function start() {
document.getElementById("main-button").style.display = "none";
document.getElementById("quiz").style.display = "block";
document.getElementById("some_div").style.display = "inline-block";
timeLeft = 70;
countdown();
timeLeftText.textContent = "Time Remaining " + timeLeft;
}
function score() {
correct = 0;
incorrect = 0;
notAnswered = 0;
var question1
var question2
var question3
var question4
var question5
var question6
var question7
var question8
var question9
var question10
// checks if the value of or radio is null.
if (document.querySelector('input[name="question1"]:checked') === null) { notAnswered++;
}
// if it has a value it logs the value
// then takes the value that was stored to the radio button and clears it; resetting or buttons.
else { question1 = document.querySelector('input[name="question1"]:checked').value;
document.querySelector('input[name="question1"]').checked=false;
// This checks the value we stored and then determines if it that value is the correct answer.
if (question1 === "d") {
correct++;
}
else if ((question1 === "a") || (question1 === "b") || (question1 === "c")) {
incorrect++;
}}
// question 2.
if (document.querySelector('input[name="question2"]:checked') === null) { notAnswered++;
}
else { question2 = document.querySelector('input[name="question2"]:checked').value;
document.querySelector('input[name="question2"]').checked=false;
if (question2 === "d") {
correct++;
}
else if (question2 === "a" || "b" || "c") {
incorrect++;
}}
// question 3.
if (document.querySelector('input[name="question3"]:checked') === null) { notAnswered++;
}
else { question3 = document.querySelector('input[name="question3"]:checked').value;
document.querySelector('input[name="question3"]').checked=false;
if (question3 === "a") {
correct++;
}
else if (question2 === "b" || "c" || "d") {
incorrect++;
}}
// question 4
if (document.querySelector('input[name="question4"]:checked') === null) { notAnswered++;
}
else { question4 = document.querySelector('input[name="question4"]:checked').value;
document.querySelector('input[name="question4"]').checked=false;
if (question4 === "d") {
correct++;
}
else if (question4 === "a" || "b" || "c") {
incorrect++;
}}
// question 5
if (document.querySelector('input[name="question5"]:checked') === null) { notAnswered++;
}
else { question5 = document.querySelector('input[name="question5"]:checked').value;
document.querySelector('input[name="question5"]').checked=false;
if (question5 === "d") {
correct++;
}
else if (question5 === "a" || "b" || "c") {
incorrect++;
}}
// question 6
if (document.querySelector('input[name="question6"]:checked') === null) { notAnswered++;
}
else { question6 = document.querySelector('input[name="question6"]:checked').value;
document.querySelector('input[name="question6"]').checked=false;
if (question6 === "c") {
correct++;
}
else if (question6 === "a" || "b" || "c") {
incorrect++;
}}
// question 7
if (document.querySelector('input[name="question7"]:checked') === null) { notAnswered++;
}
else { question7 = document.querySelector('input[name="question7"]:checked').value;
document.querySelector('input[name="question7"]').checked=false;
if (question7 === "a") {
correct++;
}
else if (question7 === "a" || "b" || "c") {
incorrect++;
}}
// question 8
if (document.querySelector('input[name="question8"]:checked') === null) { notAnswered++;
}
else { question8 = document.querySelector('input[name="question8"]:checked').value;
document.querySelector('input[name="question8"]').checked=false;
if (question8 === "b") {
correct++;
}
else if (question8 === "a" || "b" || "c") {
incorrect++;
}}
// question 9
if (document.querySelector('input[name="question9"]:checked') === null) { notAnswered++;
}
else { question9 = document.querySelector('input[name="question9"]:checked').value;
document.querySelector('input[name="question9"]').checked=false;
if (question9 === "c") {
correct++;
}
else if (question9 === "a" || "b" || "c") {
incorrect++;
}}
// question10
if (document.querySelector('input[name="question10"]:checked') === null) { notAnswered++;
}
else { question10 = document.querySelector('input[name="question10"]:checked').value;
document.querySelector('input[name="question10"]').checked=false;
if (question10 === "c") {
correct++;
}
else if (question10 === "a" || "b" || "c") {
incorrect++;
}}
// this toggles what is visible on their screen.
document.getElementById("quiz").style.display = "none";
document.getElementById("scoreBox").style.display = "block";
document.getElementById("some_div").style.display = "none";
document.getElementById("ta-button").style.display = "inline-block";
// this is the text for our score box
correctText.textContent = "Correct " + correct;
incorrectText.textContent = "Incorrect " + incorrect;
notAnsweredText.textContent = "Not Answered " + notAnswered;
}
function reset() {
// this toggles what is visible on their screen.
document.getElementById("quiz").style.display = "none";
document.getElementById("some_div").style.display = "none";
document.getElementById("ta-button").style.display = "none";
document.getElementById("scoreBox").style.display = "none";
document.getElementById("main-button").style.display = "block";
// this resets the score
correct = 0;
incorrect = 0;
notAnswered = 0;
// allows the start button to be clicked up to 20 mins after the ta button, so that the score function does start before the game.
timeLeft = 12000;
}
<div id="button-container">
<div id="ta-button">
<p id="main-button"><button type="button" class=" btn-lg btn-block text-light "
onclick="reset()"><i class="fas fa-sync"></i> Try Again? <i class="fas fa-sync"></i></button></p>
</div>
</div>
<div id="button-content" class="container">
<p id="main-button"><button type="button" class=" btn-lg btn-block text-light "
onclick="start();countdown()"><i class="fas fa-user-astronaut"></i> Start
Quiz. <i class="fas fa-user-astronaut"></i></button></p>
</div>
Try this.
var timerId = null;
var timeLeft = 70;
function countDown() {
if (timerId) {
clearTimeout(timerId);
}
//do what ever
if (timeLeft < 1) {
//do something else
//then return
return 0;
}
else {
timerId = setTimeout(countDown, 1000);
}
}
function start() {
//do whatever
timerId = setTimeout(countDown, 1000);
}
If you need more info on timers in javascript check out https://www.w3schools.com/jsref/met_win_settimeout.asp
Not in jQuery, vanilla JS.
I have the below code I'm using that works fine within the console; the problem is the 'goCheck' element does not appear right away at default, after the user crawls through a few sections, then it appears visible; because of this the event listener is hitting null immediately.
How could I get this to execute WHEN my 'goCheck' element becomes visible on page?
var goCheck = document.getElementById('input_52_65_chosen');
goCheck.addEventListener('click', function (event) {
var value1 = document.getElementById('input_52_22').value;
var value2 = document.getElementById('input_52_100').value;
var value3 = document.getElementById('input_52_95').value;
// var value4 = document.getElementById('input_52_96').value;
if (value1 > 0 ) {
document.getElementById('rate').style.display = "none";
document.getElementById('pay-plans').style.display = "none";
document.getElementById('field_52_116').style.display = "none";
} else if (value1 === 0 ) {
document.getElementById('field_52_116').style.display = "block";
}
if (value2 > 0 ) {
document.getElementById('rate').style.display = "none";
document.getElementById('pay-plans').style.display = "none";
document.getElementById('field_52_116').style.display = "none";
} else if (value2 === 0 ) {
document.getElementById('field_52_116').style.display = "block";
}
if (value3 > 0 ) {
document.getElementById('rate').style.display = "none";
document.getElementById('pay-plans').style.display = "none";
document.getElementById('field_52_116').style.display = "none";
} else if (value3 === 0 ) {
document.getElementById('field_52_116').style.display = "block";
}
if (value1 && value2 && value3 == 0 ) {
document.getElementById('field_52_116').style.display = "block";
}
}
);
Listen to every click everywhere, then check if the element you are looking for was clicked:
document.body.addEventListener("click", function(event){
const goCheck = document.getElementById('input_52_65_chosen');
let el = event.target;
while(el && el !== goCheck) el = el.parentElement;
if(!el) return;
//...
});
I'm trying to get the quiz to loop 5 times while recording the correct answer for each question before returning to start menu but I'm struggling to get it working
Any help with this will be much appreciated.
function cleartxt()
{
setTimeout("document.getElementById('ans').innerHTML = ''", 3000);
}
var random = new Array(5);
var count = 0;
function next()
{
var store = 0;
do
{
store = (Math.round(Math.ceil(Math.random() * 40) -1));
}while(random.indexOf(store) > -1);
document.getElementById("ques").innerHTML = questions[store][0];
document.getElementById("rad1").innerHTML = questions[store][1];
document.getElementById("rad2").innerHTML = questions[store][2];
document.getElementById("rad3").innerHTML = questions[store][3];
document.getElementById("rad4").innerHTML = questions[store][4];
document.getElementById("image").src = images[store];
var radio = document.getElementsByName("rad");
while(store <= 5)
{
count++;
if(store == 5)
startMenu();
if(radio[0].checked == true)
{
if(questions[store][0] == questions[store][5])
document.getElementById("ans").innerHTML = "Correct";
else
document.getElementById("ans").innerHTML = "Incorrect";
}
else if(radio[1].checked == true)
{
if(questions[store][1] == questions[store][5])
document.getElementById("ans").innerHTML = "Correct";
else
document.getElementById("ans").innerHTML = "Incorrect";
}
else if(radio[2].checked == true)
{
if(questions[store][2] == questions[store][5])
document.getElementById("ans").innerHTML = "Correct";
else
document.getElementById("ans").innerHTML = "Incorrect";
}
else if(radio[3].checked == true)
{
if(questions[store][3] == questions[store][5])
document.getElementById("ans").innerHTML = "Correct";
else
document.getElementById("ans").innerHTML = "Incorrect";
}
else
document.getElementById("ans").innerHTML = "Please select an answer!";
}
}
function startMenu()
{
window.history.back();
}
(second.innerHTML) -1 that worked but (num.innerHTML) -1 that not working why?
function doDcrements() {
var hidden = document.getElementById('hidden');
var second = document.getElementById('second'); // the second is 20.
var loopTimer = 0;
if (second.innerHTML != "0") {
second.innerHTML = (second.innerHTML) -1;
second.style.color = "blue";
loopTimer = setTimeout('doDecrements()',1000);
}else {
second.style.color = "grey";
hidden.style.display = "block";
}
}
.....................................................................................................................................................................
function doDcrements() {
var hidden = document.getElementById('hidden');
var second = document.getElementById('second'); // the second is 20.
var loopTimer = 0;
var num = document.getElementById('num'); // the number is 20.
if (second.innerHTML != "0") {
second.innerHTML = (num.innerHTML) -1;
second.style.color = "blue";
loopTimer = setTimeout('doDecrements()',1000);
}else {
second.style.color = "grey";
hidden.style.display = "block";
}
}
when I create it by for loop it not happens :
function doDcrements() {
var hidden = document.getElementById('hidden');
var second = document.getElementById('second');
for (i=20; i<=0; i--) {
if (second.innerHTML != "0") {
second.innerHTML = i;
second.style.color = "blue";
loopTimer = setTimeout('doDecrements()',1000);
}else {
second.style.color = "grey";
hidden.style.display = "block";
}
}
}
html code:
<div id="hidden">started</div>
<p id="second">20</p>
<div onClick="doDcrements();">Download</div>
Please look at your for loop:
for (i=20; i<=0; i--)
i=20 and i<=0. It will never run.
(second.innerHTML) -1 that worked but (num.innerHTML) -1 that not working why?
Without seeing your code, the only guess is that num.innerHTML is not giving you a string that is convertible to number. Examples:
'20' - 1 = 20
'<input name="xyz" val="20"/>' - 1 = NaN
Your HTML does't have any element with id="num". If this is the case, num will be null.
Changes
setTimeout(doDecrements,1000);
for (i=20; i >=0; i--)