我正在尝试模拟这样的事情:
- 点击按钮会显示一个模式弹出窗口,显示“正在加载内容”,并带有覆盖层
- 同时,我使用 jQuery 执行 ajax 调用,并启动 2 秒的计时器
- 一旦收到 ajax 调用的响应,我需要隐藏模式弹出窗口并且我的计时器结束。
我的ajax请求可能会在不到2秒的时间内返回,但我需要用户阅读弹出窗口中的消息,并且可能会在2秒后返回(但我需要它返回才能继续)。
我尝试调查 $.when 但我找不到正确设置“计时器”部分的方法。
感谢您的帮助!
最佳答案
如果您决定使用 $.when
,您可以创建一个 Deferred,它会在 x
毫秒后解析;
function timedDeferred(n) {
var deferred = jQuery.Deferred();
setTimeout(function () {
deferred.resolve();
}, n);
return deferred.promise();
}
...然后您可以使用 $.when
;
$.when($.ajax(), timedDeferred(2000)).then(function (ajax) {
// "ajax" is an array of the arguments that $.ajax() provides; see
// the bottom of http://api.jquery.com/jQuery.when/
});
关于javascript - 验证 2 个条件时执行函数 : ajax response and timer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14985840/