-1

I'm a newbie in JQuery, but I just can't find out why the if statement here doest work. You see in the code alert(a) and alert(timesRun) I put it there so i could test, if the variables did indeed count up as intended and they did.

Now is the problem: var a is determined by userinput and should make the clock stop when its equal to timesrun but the if statement seems not to work even when both alerts say: var a =12 and var timesrun is 12 the interval continues even though the if statement should have stopped it. Sorry if I'm being unclear or messy I am just at secondary school and not even native English speaker.

< script >
  $(document).ready(function () {
    $('#turnright1').click(function () {
      var a = $("#nummr1").val();
      var angle = 0;
      var timesRun = 0;
      var interval = setInterval(function () {
        timesRun += 1;
        alert(a);
        alert(timesRun);

        if (timesRun === a) {
          clearInterval(interval);
        }

        angle += 3.6;
        $('img[src^="Images/lockercenter.png"]').rotate(angle);
        i++
      }, 1000);
    });
  });
</script>
3
  • Mark the answer as accepted that helped you fix this, instead of editing question and saying: "This is fixed." That way other people can also see which was the thing that helped you along. Commented Jan 11, 2014 at 14:40
  • I know but stackoverflow didnt let me yet(had to wait 8 min) . Also im new to the site but i get it now. Commented Jan 11, 2014 at 14:47
  • Ah, ok. No worries then. :) Welcome to SO! Commented Jan 11, 2014 at 15:00

3 Answers 3

2

The problem is that $("#nummr1").val(); returns a string, and you are checking for strict equality with ===. To fix the problem, change it to

if(timesRun == a){
    clearInterval(interval);
}

` or

if(timesRun === parseInt(a)){ //or +a;
        clearInterval(interval);
}
Sign up to request clarification or add additional context in comments.

Comments

0

Since you're using the === operator, it checks for the types of the operands as well. timesRun is a Number while the value returned from the val() is a String.

You can either change the operator to == or parse the value using parseInt first

Comments

0

It is because your are using triple equals (===) in the line

if (timesRun === a) {

in order for === to work, you need to have ensure that both "timesRun" and "a" are string, or both integer, but not a mix.

for example

if (String(timesRun) === String(a)) {

or

if (parseInt(timesRun, 10) === parseInt(a, 10)) {

will work. Don't use parseInt without the second parameter or you will have bad surprises.

if (timesRun == a) {

will also work here, but double equality can de considered dangerous in Javascript.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.