我正在进行chrome扩展,我需要在其中创建一个无限循环,但每当while循环启动时,浏览器选项卡都会崩溃。我可以使用任何解决方案或其他方法吗?
答案 0 :(得分:1)
为什么需要无限循环?你想要实现什么目标?
还有其他选项,例如window.requestAnimationFrame()
,setInterval
或setTimeout
,您可以在页面内使用这些选项继续执行某些操作而不会阻止它。例如:
const counterElement = document.getElementById('counter');
let counterValue = 0;
setInterval(() => {
counterElement.innerText = (++counterValue / 100).toFixed(2);
}, 10);
body {
margin: 48px 8px 8px;
font-family: monospace;
}
#counter {
position: fixed;
top: 0;
left: 0;
width: 100%;
line-height: 32px;
padding: 0 8px;
background: black;
color: white;
}
hr {
border: none;
border-top: 2px solid black;
margin: 32px 0;
}
button {
border: 2px solid black;
background: transparent;
padding: 8px 12px;
font-family: monospace;
cursor: pointer;
outline: none;
}
button:hover {
background: yellow;
}
button:active {
background: black;
color: white;
}
button:focus {
border: 3px solid black;
padding: 7px 11px;
}
<div id="counter">0</div>
Click around the page. See how everything still works?
<hr />
<button>BUTTON</button>
<button>BUTTON</button>
根据您的需要,您还可以考虑Web Worker。