英文:
Javascript/jQuery I can't stop time with setTimeout, error find variable
问题
我使用setTimeout创建了一个5秒的时间倒计时(它有效),但我想要使用“停止”按钮来停止setTimeout,但是我在找到变量时遇到了错误。
错误是什么?
function newTime(ob) {
if(ob==undefined){
const myTimeout = setTimeout(myGreeting, 5000);
console.log("开始>");
}
if(ob=="stop"){
if(myTimeout==true){
clearTimeout(myTimeout);
console.log("停止>");
}
}
}
function myGreeting() {
document.getElementById("demo").innerHTML = "生日快乐!"
}
function myStopFunction() {
newTime("stop");
}
<h1>Window对象</h1>
<h2>setTimeout()和clearTimeout()方法</h2>
<p>点击“停止”以防止myGreeting()的执行。(你有5秒)</p>
<button onclick="myStopFunction()">停止!</button>
<button onclick="newTime()">开始新的计时</button>
<h2 id="demo"></h2>
英文:
I use setTimeout to create a time countdown of 5 seconds (it works), but I want to stop the setTimeout with Button Stop, but I have an error finding the variable.
What is the error?
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
function newTime(ob) {
if(ob==undefined){
const myTimeout = setTimeout(myGreeting, 5000);
console.log("Start>");
}
if(ob=="stop"){
if(myTimeout==true){
clearTimeout(myTimeout);
console.log("Stop>");
}
}
}
function myGreeting() {
document.getElementById("demo").innerHTML = "Happy Birthday!"
}
function myStopFunction() {
newTime("stop");
}
<!-- language: lang-html -->
<h1>The Window Object</h1>
<h2>The setTimeout() and clearTimeout() Methods</h2>
<p>Click "Stop" to prevent myGreeting() to execute. (You have 5 seconds)</p>
<button onclick="myStopFunction()">Stop!</button>
<button onclick="newTime()">new Time Start</button>
<h2 id="demo"></h2>
<!-- end snippet -->
答案1
得分: 2
You will want to move the declaration outside of your newTime function as the scope was limited to just that first call of newTime. Also use let and not const.
let myTimeout;
function newTime(ob) {
if (ob === undefined) {
myTimeout = setTimeout(myGreeting, 5000);
console.log("Start>");
}
if (ob === "stop") {
if (myTimeout) {
clearTimeout(myTimeout);
console.log("Stop>");
}
}
}
function myGreeting() {
document.getElementById("demo").innerHTML = "Happy Birthday!";
}
function myStopFunction() {
newTime("stop");
}
<h1>The Window Object</h1>
<h2>The setTimeout() and clearTimeout() Methods</h2>
<p>Click "Stop" to prevent myGreeting() from executing. (You have 5 seconds)</p>
<button onclick="myStopFunction()">Stop!</button>
<button onclick="newTime()">New Time Start</button>
<h2 id="demo"></h2>
英文:
You will want to move the declaration outside of your newTime function as the scope was limited to just that first call of newTime. Also use let and not const.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let myTimeout;
function newTime(ob) {
if(ob==undefined){
myTimeout = setTimeout(myGreeting, 5000);
console.log("Start>");
}
if(ob=="stop"){
if(myTimeout==true){
clearTimeout(myTimeout);
console.log("Stop>");
}
}
}
function myGreeting() {
document.getElementById("demo").innerHTML = "Happy Birthday!"
}
function myStopFunction() {
newTime("stop");
}
<!-- language: lang-html -->
<h1>The Window Object</h1>
<h2>The setTimeout() and clearTimeout() Methods</h2>
<p>Click "Stop" to prevent myGreeting() to execute. (You have 5 seconds)</p>
<button onclick="myStopFunction()">Stop!</button>
<button onclick="newTime()">new Time Start</button>
<h2 id="demo"></h2>
<!-- end snippet -->
答案2
得分: 1
这是因为 const
和 let
变量是块级作用域的。在你的情况下,你在 if 块内声明了 myTimeout
,所以 myTimeout
变量只会在该 if 块内可用。
为了更好地说明这一点:
1) 这会导致变量未定义错误
if (true) {
let foo = 'ok';
}
console.log(foo);
2) 而这不会:
let foo;
if (true) {
foo = 'ok';
}
console.log(foo);
此外,你必须在函数外部声明你的变量,否则你将无法访问前一次调用时分配给它的值。
英文:
That's because const
and let
variables are block-scoped. In your case, you declared myTimeout
inside the if block, so the myTimeout
variable will only be available inside that if block.
To illustrate this better:
1) This will give you a variable not defined error
if (true) {
let foo = 'ok';
}
console.log(foo);
2) This won't:
let foo;
if (true) {
foo = 'ok';
}
console.log(foo);
Also, you'll have to declare your variable outside your function, otherwise you won't have access to the value assigned to it on the previous call.
答案3
得分: 1
- 避免使用内联HTML的
on*
JS处理程序属性。改用Element.addEventListener()
代替。 - 创建一个具有所需属性和方法(如
timer.start(fn)
和timer.stop()
)的对象(单例)timer
。 - 不要忘记将timeoutId分配给变量(
timer.tOut
)并在需要时清除它。 - 创建一个
greet
函数并将其传递。
const timer = {
time: 5000,
tOut: null,
stop(callback) {
callback?.();
clearTimeout(this.tOut);
console.log("Stopped");
},
start(callback) {
this.stop(); // 停止正在进行的超时(如果有的话)
this.tOut = setTimeout(callback, this.time);
console.log("Started!");
}
};
// 用法示例:
const elDemo = document.querySelector("#demo");
const elStart = document.querySelector("#timer-start");
const elStop = document.querySelector("#timer-stop");
elStart.addEventListener("click", () => {
timer.start(() => {
elDemo.innerHTML = "Happy birthday!";
});
});
elStop.addEventListener("click", () => {
timer.stop(() => {
elDemo.innerHTML = "";
});
});
<button type="button" id="timer-start">Start New</button>
<button type="button" id="timer-stop">Stop!</button>
<h2 id="demo"></h2>
英文:
- Avoid the use of inline HTML
on*
JS handler attributes. UseElement.addEventListener()
instead - Create an Object (singleton)
timer
with the desired properties and methods liketimer.start(fn)
andtimer.stop()
- don't forget to assign the timeoutId to a variable (
timer.tOut
) and to clear it when needed. - Create a
greet
function and pass it
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const timer = {
time: 5000,
tOut: null,
stop(callback) {
callback?.();
clearTimeout(this.tOut);
console.log("Stopped");
},
start(callback) {
this.stop(); // Stop ongoing timeout (if there's any)
this.tOut = setTimeout(callback, this.time);
console.log("Started!");
}
};
// Use like:
const elDemo = document.querySelector("#demo");
const elStart = document.querySelector("#timer-start");
const elStop = document.querySelector("#timer-stop");
elStart.addEventListener("click", () => {
timer.start(() => {
elDemo.setHTML("Happy birthday!");
});
});
elStop.addEventListener("click", () => {
timer.stop(() => {
elDemo.setHTML("");
});
});
<!-- language: lang-html -->
<button type="button" id="timer-start">Start New</button>
<button type="button" id="timer-stop">Stop!</button>
<h2 id="demo"></h2>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论