【发布时间】:2021-05-26 16:46:48
【问题描述】:
我对 JS 还很陌生,知道的不多。 所以我试着做一个简单的工作倒计时,这样我就能知道我还要工作多久。它需要实际时间,只是从我必须工作的时间中减去它。非常简单。 当我将网站打开超过 20 分钟时,它会崩溃,并且 Chrome/Edge/Firefox 会显示错误消息:''SBOX_FATAL_MEMORY_EXCEEDED"。
我认为,由于事实是,我用大量的 if 来调用函数,浏览器很快就会耗尽内存。至少我是这么认为的。但我无法让它工作。没关系我如何重写我的函数,它仍然崩溃。
如果有人可以帮助我,我会很高兴,或者给我链接一个类似的 StackOverflow 问题,因为这个错误与 js 结合的少数结果对我没有帮助。
这里是JS代码:
//CSS ELEMETNS
var helloText = document.getElementById("welcomeText");
var textFiller = document.getElementById("fillerText");
var countdown = document.getElementById("countdown");
var motivationText = document.getElementById("motivationText");
var btn = document.getElementById("button");
//JS VARs
let date, hrs, mins, secs;
let date = new Date();
//main function to check which day it is, and which function to call
function clock() {
let day = date.getDay());
if (day == 0 || day == 6) {
weekend();
} else if (day == 5) {
friday();
} else {
otherDay();
}
}
//Text to display if it is sun or sat
function weekend() {
helloText.innerHTML = "Juhu!";
countdown.innerHTML = "Es ist Wochenende!";
textFiller.innerHTML = "";
btn.style.display = "none";
}
//Function to execute when it is friday
function friday() {
hrs = date.getHours();
mins = date.getMinutes();
secs = date.getSeconds();
hrs = hrs < 10 ? `0${hrs}` : hrs;
mins = mins < 10 ? `0${mins}` : mins;
secs = secs < 10 ? `0${secs}` : secs;
if (hrs >= 14 || hrs < 7) {
if ((((helloText.innerHTML != "Yeah!" &&
countdown.innerHTML != "You can go home!") &&
textFiller.innerHTML != "") &&
btn.style.display != "none")) {
helloText.innerHTML = "Yeah!";
countdown.innerHTML = "You can go home!";
textFiller.innerHTML = "";
btn.style.display = "none";
}
} else {
if (hrs < 10) {
if (helloText.innerHTML != "Good Morning!" &&
motivationText.innerHTML !=
"Man, it is still early in the morning...") {
helloText.innerHTML = "Good Morning!";
motivationText.innerHTML =
"Man, it is still early in the morning...";
}
}
if (hrs == 10 || hrs > 10) {
if (helloText.innerHTML != "Hello!" &&
motivationText.innerHTML !=
"Stay concentrated! The morning is already over!") {
helloText.innerHTML = "Hello!";
motivationText.innerHTML =
"Stay concentrated! The morning is already over!";
}
}
if (hrs == 12 || hrs > 12) {
if (motivationText.innerHTML != "You almost got it!") {
motivationText.innerHTML = "You almost got it!";
}
}
if (hrs == 13 || hrs > 13) {
if (motivationText.innerHTML !=
"Finally! The last hour!") {
motivationText.innerHTML =
"Finally! The last hour!";
}
}
hrs = 13 - hrs;
mins = 59 - mins;
secs = 60 - secs;
if (hrs < 10) {
hrs = "0" + hrs;
}
if (mins < 10) {
mins = "0" + mins;
}
if (secs < 10) {
secs = "0" + secs;
}
let time = `${hrs}:${mins}:${secs}`;
setInterval(clock, 1000);
countdown.innerText = time;
}
}
//otherday() is the same as friday(), just with different hours
【问题讨论】:
-
周五的时候,你会每秒执行一次setInterval
-
发布sn-p时,请将其设为minimal reproducible example
标签: javascript performance memory