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 abo开发者_运维技巧ut making that work?
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.
精彩评论