Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript VAR only works outside function?

  • This topic is empty.
Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #148950
    Rugg
    Participant

    Hi,

    I’m having some issues getting a set of three variables to work properly inside a simple function. It seems as if they only work as global vars outside of the associated function. Below are two test samples displaying the issue…Does anyone know what I’m doing wrong?

    Vars ouside function (working)

    http://jsfiddle.net/fmUzX/

    Vars inside function (not working)

    http://jsfiddle.net/bzrVu/

    The first example (working) forces a 3 second pause after each click event, while the second example fails and can be fired immediately without the forced pause.

    #148972
    TheDoc
    Member

    Super simple! It’s because every time you’re running the greenFunk function you’re resetting var a to be 0 so your if statement will never be true.

    #148973
    TheDoc
    Member

    If you only move the var a outside you’ll see that it works: http://codepen.io/ggilmore/pen/5c5e089e6d371d9eb7b9a9b1425f69e1

    Also you’ll notice that I threw in a bunch of console logs there. They are super helpful for debugging these sorts of things. On my two clicks I get this in the Console:

    1378274053878
    1378274053878
    3100
    false
    1378274055173
    1295
    3100
    true
    
Viewing 3 posts - 1 through 3 (of 3 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.