-2

http://jsfiddle.net/75pxp9ms/5/

In the JSfiddle i have above, im asking it to change the text of the id "text" when the counter variable is under and over ten but it doesn't seem to be working, was wondering if anyone could help me out! It's probably a really easy fix but im fairly new to javascript so forgive me, ill get the hang of it

thanks

    var counter = 0;
var value = 1;
var spin = document.getElementById("var");
var lol = document.getElementById("text");

setInterval(function () {
    counter += value;
    spin.innerHTML = counter;

}, 1000);

if (counter > 10) {
    lol.innerHTML = "WOW YOU REALLY LOVE KEVIN XO"
}

edit: Sorry for duplicate post and thanks for the help guys!

BobK
  • 35
  • 6
  • The interval is asynchronous, it updates the counter at a later time, while the if statement is checked right now, not later when the value is updated – adeneo Mar 18 '15 at 21:52
  • 2
    You are executing the `if` statement before `counter` is ever incremented. – Felix Kling Mar 18 '15 at 21:52

2 Answers2

2

Your if only executes once, when counter is 0.

If you want it to execute repeatedly, you need to put inside your setInterval callback.

user229044
  • 232,980
  • 40
  • 330
  • 338
1

By the time your setInterval finishes, your if statement has already been evaluated. Better solution:

var counter = 0;
var value = 1;
var spin = document.getElementById("var");
var lol = document.getElementById("text");

setInterval(function () {
    counter += value;
    spin.innerHTML = counter;
    if (counter > 10) {
      lol.innerHTML = "WOW YOU REALLY LOVE KEVIN XO"
    }

}, 1000);
Bwaxxlo
  • 1,860
  • 13
  • 18