[英]How to make js in my website more efficient?
所以我想要做的是,我正在使用 js 更改 div 的背景。 代碼是:
let counter = 0;
setInterval(() => {
counter ++;
if(counter == 3) counter = 0;
switch (counter) {
case 0 : {
background1.style.zIndex = "-1";
background2.style.zIndex = "-2";
background3.style.zIndex = "-2";
background1.style.opacity = "1";
background2.style.opacity = "0";
background3.style.opacity = "0";
break;
}
case 1 : {
background2.style.zIndex = "-1";
background1.style.zIndex = "-2";
background3.style.zIndex = "-2";
background2.style.opacity = "1";
background3.style.opacity = "0";
background1.style.opacity = "0";
break;
}
case 2 : {
background3.style.zIndex = "-1";
background1.style.zIndex = "-2";
background2.style.zIndex = "-2";
background3.style.opacity = "1";
background1.style.opacity = "0";
background2.style.opacity = "0";
break;
}
}
}, 25000);
主要的收獲是,我每 25 秒在 js 中運行一次 function。
現在假設 25 秒即將結束。 然后我單擊一個“按鈕”,Idk 運行一些 animation 和東西,然后 ofc,js 是單線程的,將對任務進行排隊,它看起來有點滯后,好像“按鈕”不起作用.
這並不是什么糟糕的用戶體驗,因為背景更改 function 並沒有做太多繁重的任務。 所以我應該忽略它,並希望用戶也忽略它,或者你會怎么做? 謝謝。
JavaScript 的setInterval
function 是異步的,所以它在“等待”state 時不會阻塞主流程。 您單擊一個按鈕來執行一些 animation 或其他事情可能會導致您上面所說的滯后,我認為您可以使用requestAnimationFrame實現一個令人窒息的 animation,因為如果處理器不是很忙,它可以達到 60fps。 這是一個示例代碼 snippet 可能會有所幫助:
function update() {
let elapsedTime = Date.now() - startedAt
// playback is a value between 0 and 1
// being 0 the start of the animation and 1 its end
let playback = elapsedTime / duration
updateTarget(playback)
if (playback > 0 && playback < 1) {
// Queue the next frame
requestAnimationFrame(update)
} else {
// Wait for a while and restart the animation
setTimeout(start, duration/10)
}
}
我認為您完全不通過 Javascript 而是純粹在 CSS 中使用 animation 來獲得更好的性能。 這樣系統就可以在可能的情況下使用硬件 (GPU),並且不會弄亂 JS。
這是一個簡單的示例,顯然您想放入自己的圖像,如果背景是用於除主體以外的某些元素,則將 CSS 更改為此。
body { width: 100vw; height: 100vh; animation-name: change; animation-duration: 75s; animation-iteration-count: infinite; } @keyframes change { 0% { background: red; } 0.01% { background: green; } 33% { background: green; } 33.01% { background: blue; } 66% { background: blue; } 66.01% { background: red; } 99.99% { background: red; } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.