(if) 条件的新值无效
The new value for the (if) condition has no effect
我有一个 JS 代码块,如下所示。该代码将在 30 秒后将用户重定向到登录页面,但如果用户单击页面上的任何位置,该过程将被重置。理论上代码逻辑是正确的 setInterval
和 EventListener
都工作正常但是当我点击页面中的某个地方时虽然全局变量(计数器)更改为 0 但是(如果)setInterval
中的条件有没有效果,仍然(计数器)变量保持不变,重定向将会发生!!!
var counter = 0;
setInterval(function() {
if (counter >= 30) {
// commented below line for testing with run code in stack overflow.
// In real code it will be uncommented.
// document.location = 'http://localhost/login';
console.log('redirect');
} else {
counter++;
}
}, 1000);
document.addEventListener('click', function(e) {
counter = 0;
}, true);
您的代码应该可以工作
这里是一个使用 clearInterval
的可能更容易理解的版本
let secs = 5;
let tId;
function int() {
clearInterval(tId);
counter = secs;
tId = setInterval(function() {
if (counter <= 0) {
document.location = 'https://github.com';
} else {
counter--;
}
document.getElementById("x").innerText = counter
}, 1000);
}
document.addEventListener('click', int);
int()
<span id="x"></span>
我有一个 JS 代码块,如下所示。该代码将在 30 秒后将用户重定向到登录页面,但如果用户单击页面上的任何位置,该过程将被重置。理论上代码逻辑是正确的 setInterval
和 EventListener
都工作正常但是当我点击页面中的某个地方时虽然全局变量(计数器)更改为 0 但是(如果)setInterval
中的条件有没有效果,仍然(计数器)变量保持不变,重定向将会发生!!!
var counter = 0;
setInterval(function() {
if (counter >= 30) {
// commented below line for testing with run code in stack overflow.
// In real code it will be uncommented.
// document.location = 'http://localhost/login';
console.log('redirect');
} else {
counter++;
}
}, 1000);
document.addEventListener('click', function(e) {
counter = 0;
}, true);
您的代码应该可以工作
这里是一个使用 clearInterval
的可能更容易理解的版本let secs = 5;
let tId;
function int() {
clearInterval(tId);
counter = secs;
tId = setInterval(function() {
if (counter <= 0) {
document.location = 'https://github.com';
} else {
counter--;
}
document.getElementById("x").innerText = counter
}, 1000);
}
document.addEventListener('click', int);
int()
<span id="x"></span>