0

I have two functions, one that makes an Ajax request when the user loads the page, and one that will run every 5 or so seconds to update something. Using the first function, I can output a variable that I need to use in the second function.

function insert_last_ten() {
    $.ajax({
       url: 'freeshout/chatlog.php',
       success: function(data) {
         $("#inner-wrap").html(data);
         var first_child = $("#inner-wrap :first-child").html();
         var value = first_child.match(/(value)=["']?((?:.(?!["']?\s+(?:\S+)=|[>"']))+.)["']?/);
         var realtime = value[2];
       }
     });
    }

Basically, I need to use realtime to do something else in another function. For the sake of simplicity, let's pretend this is the second function:

function update() {
    alert(realtime);
}

How could I go about making that work?

2
  • Can you move realtime out to a more public scope? Commented Jan 24, 2011 at 21:38
  • Making realtime a global variable would be the easy way. Commented Jan 24, 2011 at 21:39

1 Answer 1

2

In the success callback, cancel the timeout and start a new one using the updated value. You can pass the timeout identifier to insert_last_ten via argument and the success callback will pick it up via closure:

function createUpdateTimer(value, interval) {
    return setTimout(
      function () {
        alert(value); // The created function knows what value is due to closure
      }, interval);
}

function insert_last_ten(timer) {
    $.ajax({
        url: 'freeshout/chatlog.php',
        success: function(data) {
            $("#inner-wrap").html(data);
            var first_child = $("#inner-wrap :first-child").html();
            var value = first_child.match(/(value)=["']?((?:.(?!["']?\s+(?:\S+)=|[>"']))+.)["']?/);
            var realtime = value[2];
            cancelTimer(timer); // This callbac knows what timer is due to closure
            timer = createUpdateTimer(realtime, 500);
        }
    });
}

// Start the timer:
var timer = createUpdateTimer('initial value', 500);

// Make ajax request:
insert_last_ten(timer);

Note that I am only beginning to familiarize myself with the good parts of JavaScript. This code is untested.

Sign up to request clarification or add additional context in comments.

2 Comments

How would I go about that? I checked through jQuery docs and searched around, and couldn't really find out what you mean. =/
@Andrew: I updated my answer with an example. Closures are not in the jQuery documentation, because it's a JavaScript feature, not a jQuery feature.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.