JavaScript / jQuery: 如何在重定向前正确使用 setTimeout

JavaScript / jQuery: How to properly use setTimeout before redirect

我是 JS 的新手,希望有人能帮助我解决这个问题。

我正在尝试淡出 div,然后 等待两秒钟,然后重定向 到另一个页面。

到目前为止,我有以下内容可以根据需要进行重定向,但我认为我没有正确使用 setTimeout,因为重定向总是立即发生,与我为超时设置的值无关。

有人可以告诉我我必须如何组合它以便 JS 在重定向之前等待吗? 我想使用 setTimeout 而不是延迟等,如果可能的。

setTimeout(function(){ $(that).closest('div.boxBlueOuter').fadeOut(), 2000 });
// redirect to index page
window.location.href = baseURL + '/index.php?lang=' + selectedLang;

非常感谢, 麦克

.fadeOut() 可以回调,这就是它的样子

.fadeOut( [duration ] [, complete ] )

首先使用淡出,在回调中有一个超时2秒,然后重定向。 应该做这样的事情。

$(that).closest('div.boxBlueOuter').fadeOut(function(){
  setTimeout(function(){
    window.location.href = baseURL + '/index.php?lang=' + selectedLang;
  }, 2000);
});

不幸的是,setTimeout 不是实际 EcmaScript 规范的一部分,因此它的行为在执行环境中可能不一致。

根据https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout

说的

Firefox 中的setTimeout 将在指定的延迟后执行传入的函数。目前您指定在 2 秒延迟后淡出。相反,您想在 2 秒延迟后像这样重定向

$(that).closest('div.boxBlueOuter').fadeOut()

setTimeout(function(){ window.location.href = baseURL + '/index.php?lang=' + selectedLang;}, 2000 );

我会推荐使用标准化的东西,避免 setTimeout。