javascript - 验证 2 个条件时执行函数 : ajax response and timer

标签 javascript jquery timer request

我正在尝试模拟这样的事情:

  • 点击按钮会显示一个模式弹出窗口,显示“正在加载内容”,并带有覆盖层
  • 同时,我使用 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/

相关文章:

javascript - 跨域ajax请求不发送响应

javascript - 使用 div 的值传递数据(安全)

javascript - jQuery 更改悬停时引导图标的路径

java - 在计时器中使用 "if"语句执行任务而不满足指定条件?

c# - 为什么Windows.Forms.Timer的时间间隔随着tick的增加而减少?

javascript - 如何从头开始创建 IFC 文件?

javascript - js setTimeout 同步

javascript - iPad/Android 平板电脑上的 HTML5 Canvas(游戏)

jquery - 如何将多选中的值数组传递到 jquery ajax 调用中?

c# - 高性能定时器与秒表