0

The following javascript code is for a "ping-pong" game I was asked to make:

var final_number = document.getElementById("input").value;
var current_number = 0;

var interval = setInterval(document.getElementById("submit").onclick = function() {
    document.getElementById('number').innerHTML = ++current_number;
    if (current_number % 3 === 0){
        document.getElementById('number').innerHTML = "ping";
    }
    if (current_number % 5 === 0){
        document.getElementById('number').innerHTML = "pong";
    }   
    if (current_number % 15 === 0){
        document.getElementById('number').innerHTML = "ping";
        document.getElementById('number').innerHTML = "pong";
    }    
    if (current_number >= final_number){
        document.getElementById('number').innerHTML = 'Game Over';
        clearInterval(interval);
    }
}, 1000);

It counts up from 0 to the number inputted in the form "input" in the html then says 'Game Over' when it reaches the number. The problem, however, is that it immediately says 'Game Over' without counting at all. I think the problem is with fetching the form value. It worked until iI introduced the variable "final_number" and put it in the last if statement (I used the number 50 before). Any ideas how to fix this?

1
  • You could use a debugger to actually see what's going on. Commented Feb 25, 2018 at 15:29

2 Answers 2

3

You need to use parseInt when getting the value, otherwise it will be a string

var final_number = parseInt(document.getElementById("input").value,10);
Sign up to request clarification or add additional context in comments.

Comments

1

You are comparing a number with a Text so its comparing ASCII values , I think that you need to convert your value first

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.