[英]how can I set a setInterval as a global variable?
I just wanna make a button to start adding some text in my body, and a button to stop adding this text.我只想制作一个按钮来开始在我的正文中添加一些文本,以及一个停止添加此文本的按钮。
I figured out that I can use a setTimeout in a function or a setInterval...but I couldn't Clear both of them because of the local scope...I can't declare both of them as a global scope, I want my button.onclick activate them not by default.我发现我可以在函数或 setInterval 中使用 setTimeout ......但由于局部范围我无法清除它们......我不能将它们都声明为全局范围,我想要我的 button.onclick 不是默认激活它们。
/* global document*/ var myStart = document.querySelector('#start'), myEnd = document.querySelector('#end'), myRepeat; function start() { "use strict"; document.body.innerHTML += '<br>Welcome StackOverFlowMembers!'; myRepeat = setTimeout(start, 1000) } function stop() { "use strict"; clearTimeout(myRepeat); } myStart.onclick = start; myEnd.onclick = stop;
<body> <button id="start">Start!</button> <button id="end">End!</button> <script src="script.js"></script> </body>
The problem here is not the scope of the variables.这里的问题不在于变量的范围。 Everything is actually fine with your code on that.
你的代码实际上一切都很好。
The problem is here:问题在这里:
document.body.innerHTML += '<br>Welcome StackOverFlowMembers!';
If you replace it with:如果您将其替换为:
console.log('Hello!');
Both buttons will work normally.两个按钮都会正常工作。 Check this fiddle .
检查这个小提琴。
Basically, when you use innerHTML
you destroy the event listeners.基本上,当您使用
innerHTML
您会破坏事件侦听器。 You can find more on that in this answer您可以在此答案中找到更多相关信息
As @anpel's answer explains, your innerHTML
call is trashing your event listeners.正如@anpel 的回答所解释的那样,您的
innerHTML
调用正在破坏您的事件侦听器。 In the code below, I work around that by putting the onclick
attribute directly into the HTML button elements.在下面的代码中,我通过将
onclick
属性直接放入 HTML 按钮元素来解决这个问题。 The boolean doRepeat
variable governs whether a subsequent timeout gets initiated.布尔
doRepeat
变量控制是否启动后续超时。
/* global document*/ var myStart = document.querySelector('#start'), myEnd = document.querySelector('#end'), doRepeat; function start() { "use strict"; document.body.innerHTML += '<br>Welcome StackOverFlowMembers!'; if (doRepeat) { setTimeout(start, 1000); } }
<body> <button id="start" onclick="doRepeat=true;start();">Start!</button> <button id="end" onclick="doRepeat=false;">End!</button> <script src="script.js"></script> </body>
Alternatively, you can make a separate <div>
into which your function writes its text-- instead how you're doing innerHTML
to the entire HTML body , which destroys all child listeners-- and you won't have to worry about your event listeners getting destroyed since those listeners aren't on children of the target div.或者,您可以制作一个单独的
<div>
,您的函数将其文本写入其中 - 而不是您如何对整个 HTML body执行innerHTML
,这会破坏所有子侦听器 - 您不必担心您的事件侦听器被销毁,因为这些侦听器不在目标 div 的子级上。
Here's a JS Fiddle to demonstrate that: https://jsfiddle.net/j9voxg7s/这是一个 JS Fiddle 来证明这一点: https : //jsfiddle.net/j9voxg7s/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.