Jak*_*mos 4 javascript ajax jquery
下面的代码逻辑是否会导致原始调用的堆栈帧包含每次后续调用的内存(导致过多的内存使用)?
function foo (arg) {
bar(arg);
}
function bar (arg) {
$.ajax({
success: function (data) {
if (data['result'] == 'continue') {
bar(data['nextarg']);
} else if (data['result'] == 'done') {
alert('done!');
}
}
});
}
Run Code Online (Sandbox Code Playgroud)
您的代码不是递归的.$.ajax是异步的,因此堆栈指针不等待bar返回.
相反,$.ajax触发异步进程,然后继续,直到它遇到显式或隐式返回.在你的情况下,在结尾处有一个隐含的回报bar.
你的功能消耗的内存不会超过预期.
function bar (arg) {
// calls $.ajax, which is async, so it fires "whenever"
$.ajax({
// when the ajax is complete/successful, this function is called
success: function (data) {
if (data['result'] == 'continue') {
bar(data['nextarg']);
} else if (data['result'] == 'done') {
alert('done!');
}
}
})
// exits immediately after
}
Run Code Online (Sandbox Code Playgroud)