Rob Rob - 7 months ago 18
Javascript Question

Javascript code block finishes BEFORE it gets back the result of a called function? What am I missing?

As the title says, I have a block of Javascript code in a .JS file. Here I call a function in a seperate ASCX file which changes the x variable.

$('#button').bind('click', function (event) {

if(x == true){do something}
if(x == false){do something else}

In the ASCX file I have the variable and the function:

var x;
function Function(){
if(y > 100)
x = true
if(y < 100)
x = false

I would expect that, if the button is clicked, the function would execute (which it does), the variable would change depending on the conditions (which also happens). However, the code uses the value of x of how it was BEFORE the code ran.

So if x was true before the button was clicked, and one would click the button, the outcome would always evaluate as true even if the conditions of y should actually have x evaluate as false.

I am not sure why this is happening. Merging the files so that both the function and the call are in the same location is unfortunately not an option. Any input would be greatly appreciated.

Kind regards, Rob


You can return it from Function. You can check further using returned value.

You dont need to assign and check for update in calling context.

One JS file :

$('#button').bind('click', function(event) {
    x = Function();

    if(x == true) { //do something }

    if(x == false) { 
        //do something else

Second JS file :

function Function() {
    if (y > 100)
        return true
    if (y < 100)
        return false