0

Say I have a function like this:

var some_value = 0
function refresh(something)
{
    // Log our value
    console.log(some_value);

    // If this function was invoked by clicking our some_div created below, set some_value
    if(last.getAttribute("baby"))
    {
        some_value = 1;
    }

    // Create some div, give it a random attribute and add an onclick event
    some_div.setAttribute("baby");
    some_div.addEventListener("click", function(){refresh(this);}, false);

    // Log our some_value
    console.log(some_value);
}

// Call our function
refresh(null)

I would expect the console to look like this:

//refresh(null)
0
0

//clicked our some_div
0
1

Instead if looks like this:

//refresh(null)
0
0

//clicked our some_div
1
1

When is my some_value being set? This is making me crazy. I would really appreciate some help...

Jason Song
  • 21
  • 3

1 Answers1

0

var some_value = 0 is executed just once as it is outside the function. After the first time you click on a div, some_value is set as 1. You may have accidentally clicked that. The next time you call the refresh() by clicking on a div, some_value has value 1 previously set. Then result will be

1
1

To get your desired result, make some_value a local variable inside refresh.

function refresh(something)
{
var some_value = 0 #value is initialised every time
.
.
.
}

Will give

0
1

Every time you click on a div.

Sreeragh A R
  • 2,871
  • 3
  • 27
  • 54