JavaScript/jQuery 我无法使用 setTimeout 停止时间,错误找到变量

huangapple go评论62阅读模式
英文:

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(&quot;Start&gt;&quot;);
    }
	if(ob==&quot;stop&quot;){
    	if(myTimeout==true){
    		clearTimeout(myTimeout);
        	console.log(&quot;Stop&gt;&quot;);
        }
    }
    
}

function myGreeting() {
  document.getElementById(&quot;demo&quot;).innerHTML = &quot;Happy Birthday!&quot;
}

function myStopFunction() {
  newTime(&quot;stop&quot;);
}

<!-- language: lang-html -->

&lt;h1&gt;The Window Object&lt;/h1&gt;
&lt;h2&gt;The setTimeout() and clearTimeout() Methods&lt;/h2&gt;

&lt;p&gt;Click &quot;Stop&quot; to prevent myGreeting() to execute. (You have 5 seconds)&lt;/p&gt;

&lt;button onclick=&quot;myStopFunction()&quot;&gt;Stop!&lt;/button&gt;
&lt;button onclick=&quot;newTime()&quot;&gt;new Time Start&lt;/button&gt;

&lt;h2 id=&quot;demo&quot;&gt;&lt;/h2&gt;

<!-- 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(&quot;Start&gt;&quot;);
    }
    if(ob==&quot;stop&quot;){
        if(myTimeout==true){
            clearTimeout(myTimeout);
            console.log(&quot;Stop&gt;&quot;);
        }
    }
    
}

function myGreeting() {
  document.getElementById(&quot;demo&quot;).innerHTML = &quot;Happy Birthday!&quot;
}

function myStopFunction() {
  newTime(&quot;stop&quot;);
}

<!-- language: lang-html -->

&lt;h1&gt;The Window Object&lt;/h1&gt;
&lt;h2&gt;The setTimeout() and clearTimeout() Methods&lt;/h2&gt;

&lt;p&gt;Click &quot;Stop&quot; to prevent myGreeting() to execute. (You have 5 seconds)&lt;/p&gt;

&lt;button onclick=&quot;myStopFunction()&quot;&gt;Stop!&lt;/button&gt;
&lt;button onclick=&quot;newTime()&quot;&gt;new Time Start&lt;/button&gt;

&lt;h2 id=&quot;demo&quot;&gt;&lt;/h2&gt;

<!-- end snippet -->

答案2

得分: 1

这是因为 constlet 变量是块级作用域的。在你的情况下,你在 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 = &#39;ok&#39;; 
}
console.log(foo);

2) This won't:

let foo;
if (true) {
    foo = &#39;ok&#39;; 
}
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. Use Element.addEventListener() instead
  • Create an Object (singleton) timer with the desired properties and methods like timer.start(fn) and timer.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(&quot;Stopped&quot;);
  },
  start(callback) {
    this.stop(); // Stop ongoing timeout (if there&#39;s any)
    this.tOut = setTimeout(callback, this.time);
    console.log(&quot;Started!&quot;);
  }
};

// Use like:
const elDemo = document.querySelector(&quot;#demo&quot;);
const elStart = document.querySelector(&quot;#timer-start&quot;);
const elStop = document.querySelector(&quot;#timer-stop&quot;);

elStart.addEventListener(&quot;click&quot;, () =&gt; {
  timer.start(() =&gt; {
    elDemo.setHTML(&quot;Happy birthday!&quot;);
  });
});

elStop.addEventListener(&quot;click&quot;, () =&gt; {
  timer.stop(() =&gt; {
    elDemo.setHTML(&quot;&quot;);
  });
});

<!-- language: lang-html -->

&lt;button type=&quot;button&quot; id=&quot;timer-start&quot;&gt;Start New&lt;/button&gt;
&lt;button type=&quot;button&quot; id=&quot;timer-stop&quot;&gt;Stop!&lt;/button&gt;
&lt;h2 id=&quot;demo&quot;&gt;&lt;/h2&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年6月16日 01:36:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76484205.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定