【发布时间】:2021-09-02 09:01:12
【问题描述】:
问题陈述: 作为一名开发人员,我想开发一种打字动画效果,只要页面处于活动状态,它就应该在页面上运行,而不会导致页面上出现任何性能问题(内存泄漏)。
问题我现在面临的是我的代码导致了我想避免的内存泄漏。
这是我迄今为止开发的。
let loopAnimation = true;
let animationTimeout;
let animationBase = 'Develop in ';
let animationPool = ['HTML', 'CSS', 'JavaScript'];
let animationCounter = 0;
let animation = animationBase + animationPool[animationCounter];
let i = 1;
let timeoutReadable = 1750;
let timeoutTyping = 100;
let timeoutDeleting = 70;
let span = document.getElementById('animationtextbox');
let forwarding = false;
let currentWord;
function sleep(ms) {
return new Promise((resolve) => {
animationTimeout = setTimeout(() => {
resolve();
return null;
}, ms);
});
}
textAnimation();
async function textAnimation() {
while (loopAnimation) {
currentWord = null;
currentWord = animationPool[animationCounter];
if (forwarding) {
if (i < currentWord.length) {
// play effect (type word)
span.innerText =
animationBase + currentWord.slice(0, i - currentWord.length);
i++;
forwarding = true;
await sleep(timeoutTyping);
} else {
span.innerText = animationBase + currentWord;
i = 1;
forwarding = false;
await sleep(timeoutReadable);
}
} else {
if (i <= currentWord.length) {
// play effect (remove word)
span.innerText =
animationBase + animationPool[animationCounter].slice(0, i * -1);
i++;
forwarding = false;
await sleep(timeoutDeleting);
} else {
// switch animation word
i = 1;
if (animationCounter < animationPool.length - 1) {
animationCounter++;
} else {
animationCounter = 0;
}
forwarding = true;
await sleep(timeoutTyping);
}
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<span id="animationtextbox"></span>
</body>
</html>
【问题讨论】:
-
这似乎不是递归的?您只调用一次
textAnimation(),在textAnimation()调用之外,从不调用内部。 (并且您的sleep()函数不会调用自身) -
对不起,我的问题措辞有点错误。动画功能使用while循环循环
标签: javascript performance animation memory memory-leaks