Javascript - 如何创建一个定时重定向按钮和一个不同的按钮来取消它
Javascript - how to create a timed redirect button and a different button to cancel it
我有以下代码。按下第一个按钮会在 10 秒后将用户发送到另一个 URL。
但是,如果在这 10 秒之前按下第二个按钮,我也会尝试取消该重定向。这似乎不起作用,URL 重定向仍然发生。
我在网上查找了各种解决方案,但都无法正常工作。我还尝试用 setInterval/clearInterval 和其他代码变体替换 setTimeout/clearTimeout。
我愿意完全更改代码或使用 Jquery 等。过去几天我一直在尝试这样做,因此非常感谢任何帮助。
如果在按下第二个按钮后再次按下第一个按钮,重定向倒计时也可以从10秒重新开始,那也很好。
Javascript
<script>
var redirectTime = "10000";
var redirectURL = "https://realmbound.com";
function timedRedirect() {
var timeoutHandle = window.setTimeout("location.href = redirectURL;",redirectTime);
}
function stopTimer() {
clearTimeout(timeoutHandle);
}
</script>
HTML
<button onclick="JavaScript:timedRedirect()">Click me for a timed redirect.</button>
<button onclick="JavaScript:stopTimer()">Stop Timer.</button>
您的 timeoutHandle
在作用域函数中,您必须按顺序将其 delcare 到全局作用域才能在 stopTimer()
.
上访问它
let redirectTime = "1000";
let redirectURL = "https://realmbound.com";
let timeoutHandle;
function timedRedirect() {
timeoutHandle = window.setTimeout("location.href = redirectURL;",redirectTime);
}
function stopTimer() {
clearTimeout(timeoutHandle);
}
<button onclick="JavaScript:timedRedirect()">Click me for a timed redirect.</button>
<button onclick="JavaScript:stopTimer()">Stop Timer.</button>
其余代码没问题。
您的解决方案是正确的,您唯一遗漏的是将 timeoutHandle
变量作为全局范围,以便 stopTimer
函数可以访问它。
这是您的解决方案的工作修复版本:
https://jsfiddle.net/8uw7f19k/1/
希望对您有所帮助 ;-)
我有以下代码。按下第一个按钮会在 10 秒后将用户发送到另一个 URL。
但是,如果在这 10 秒之前按下第二个按钮,我也会尝试取消该重定向。这似乎不起作用,URL 重定向仍然发生。
我在网上查找了各种解决方案,但都无法正常工作。我还尝试用 setInterval/clearInterval 和其他代码变体替换 setTimeout/clearTimeout。
我愿意完全更改代码或使用 Jquery 等。过去几天我一直在尝试这样做,因此非常感谢任何帮助。
如果在按下第二个按钮后再次按下第一个按钮,重定向倒计时也可以从10秒重新开始,那也很好。 Javascript
<script>
var redirectTime = "10000";
var redirectURL = "https://realmbound.com";
function timedRedirect() {
var timeoutHandle = window.setTimeout("location.href = redirectURL;",redirectTime);
}
function stopTimer() {
clearTimeout(timeoutHandle);
}
</script>
HTML
<button onclick="JavaScript:timedRedirect()">Click me for a timed redirect.</button>
<button onclick="JavaScript:stopTimer()">Stop Timer.</button>
您的 timeoutHandle
在作用域函数中,您必须按顺序将其 delcare 到全局作用域才能在 stopTimer()
.
let redirectTime = "1000";
let redirectURL = "https://realmbound.com";
let timeoutHandle;
function timedRedirect() {
timeoutHandle = window.setTimeout("location.href = redirectURL;",redirectTime);
}
function stopTimer() {
clearTimeout(timeoutHandle);
}
<button onclick="JavaScript:timedRedirect()">Click me for a timed redirect.</button>
<button onclick="JavaScript:stopTimer()">Stop Timer.</button>
其余代码没问题。
您的解决方案是正确的,您唯一遗漏的是将 timeoutHandle
变量作为全局范围,以便 stopTimer
函数可以访问它。
这是您的解决方案的工作修复版本: https://jsfiddle.net/8uw7f19k/1/
希望对您有所帮助 ;-)