[英]Passing variables between functions
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. 我有两个功能,一个在用户加载页面时发出Ajax请求,另一个将每5秒钟运行一次以更新某些内容。 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. 基本上,我需要使用
realtime
在其他函数中执行其他操作。 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? 我该如何进行这项工作?
In the success
callback, cancel the timeout and start a new one using the updated value. 在
success
回调中,取消超时并使用更新后的值开始一个新的超时。 You can pass the timeout identifier to insert_last_ten
via argument and the success
callback will pick it up via closure: 您可以通过参数将超时标识符传递给
insert_last_ten
, success
回调将通过闭包进行接收:
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. 请注意,我才刚刚开始熟悉JavaScript的优秀部分。 This code is untested.
此代码未经测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.