我有一个代码,可以确定网站上的访问者使用哪种语言,并将用户转到正确的页面。我想在转发用户之前添加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>
答案 0 :(得分:1)
使用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);
}
答案 1 :(得分:0)
使用此setTimeout
或setInterval
,例如:
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);
}
答案 2 :(得分:0)
如果不想使用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');