[英]how can I set a setInterval as a global variable?
我只想制作一個按鈕來開始在我的正文中添加一些文本,以及一個停止添加此文本的按鈕。
我發現我可以在函數或 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>
正如@anpel 的回答所解釋的那樣,您的innerHTML
調用正在破壞您的事件偵聽器。 在下面的代碼中,我通過將onclick
屬性直接放入 HTML 按鈕元素來解決這個問題。 布爾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>
或者,您可以制作一個單獨的<div>
,您的函數將其文本寫入其中 - 而不是您如何對整個 HTML body執行innerHTML
,這會破壞所有子偵聽器 - 您不必擔心您的事件偵聽器被銷毀,因為這些偵聽器不在目標 div 的子級上。
這是一個 JS Fiddle 來證明這一點: https : //jsfiddle.net/j9voxg7s/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.