javascript 延迟确定用户语言[关闭]

sxpgvts3  于 2023-04-19  发布在  Java
关注(0)|答案(3)|浏览(136)

已关闭,该问题需要details or clarity,目前不接受回答。
**想要改进此问题?**通过editing this post添加详细信息并澄清问题。

3年前关闭。
Improve this question
我有一个代码,它可以确定网站上的访问者使用的语言,并将用户转发到正确的页面。我想在转发用户之前添加3秒的延迟。这是可行的吗?

<script>
  var lang = window.navigator.language;
  var userLang = window.navigator.userLanguage;
  if(window.location.href.indexOf('/?edit') === -1) {
    if (lang == "sv-SE" || userLang == "sv-SE") {
      window.location.href = window.location.href + "se";
    } else {
      window.location.href = window.location.href + "en";
    }
  }
</script>
ercv8c1e

ercv8c1e1#

使用setTimeout在指定的超时后触发函数调用。

if (window.location.href.indexOf('/?edit') === -1) {
  const lang = window.navigator.language;
  const userLang = window.navigator.userLanguage;
  let pageLang = 'en';

  if (lang == "sv-SE" || userLang == "sv-SE") pageLang = 'se';

  window.setTimeout(() => {
    window.location.href += pageLang;
  }, 3000);
}
yeotifhr

yeotifhr2#

使用setTimeoutsetInterval如下:

setTimeout(function(){ 
// any staff
},3000);

对你来说就像:

if (lang == "sv-SE" || userLang == "sv-SE") {
setTimeout(function(){ 
      window.location.href = window.location.href + "se";
},3000);
    } else {
setTimeout(function(){ 
      window.location.href = window.location.href + "en";
},3000);
    }
e37o9pze

e37o9pze3#

如果不想使用setTimeout,可以使用sleep()

function sleep( millisecondsToWait )
{
    var now = new Date().getTime();
    while ( new Date().getTime() < now + millisecondsToWait )
    {
        /* do nothing; this will exit once it reaches the time limit */
        /* if you want you could do something and exit */
    }
}

console.log('something');
sleep(3000);
console.log('hello');

相关问题