6 秒的 setInterval 执行过多

setInterval with 6 seconds way too much executes

我正在尝试制作一个程序,使 chrome 页面随着所需时间的临近而逐渐亮起,以便它模仿阳光,并且我可以更成功地使用显示器的灯唤醒。

我正在使用p5.js,我的代码如下。

index.html :

<!DOCTYPE html>
<html>
    <head>
        <script src='../p5.min.js'></script>
        <script src='sketch.js'></script>
    </head>
    <body style="margin:0;">
    </body>
</html>

sketh.js :

function setup(){
    createCanvas(1920, 1076);
    background(0);
}

function draw(){
    var steps = 5;                               // How many steps of brightness I want
    rectMode(CORNERS)
    fill(random(0, 255), random(0, 255), random(0, 255), 40)
    window.setInterval(function(){               // Set interval for checking

        // I added additionally from here ---------------------------------------------
        setTimeout(function() {
            window.location.reload(false);
        }, 2000)
        // Up to here -----------------------------------------------------------------

        var date = new Date();
        var hours = 1;                           // Hour that I want to wake up
        var minutes = 55;                        // Minute that I want to wake up

        var wholeThing = hours * 60 + minutes;
        var currentWholeThing = (date.getHours() * 60 + date.getMinutes());
        var diff = wholeThing -  currentWholeThing;

        if ( diff <= steps && diff >= 0)
        {
            var color = 1 - (diff / steps);
            console.log(color);
            background(Math.floor(255 * color), Math.floor(205 * color), Math.floor(153 * color))
        }

        console.log(date.getHours(), date.getMinutes(), date.getSeconds())
    }, 6000);
}

并且我从here下载了p5.min.js,并从这两个源文件中添加了上层目录中的文件。

最后,我使用 SO 帖子 here 中的代码来捕捉小时和分钟。但是我 运行 遇到了检查时间和选择颜色的主要功能执行过多的问题。 Duplicate final console.log 每秒出现多次。(更不用说我打算让整个函数每 6 秒执行一次)

所以我查找了来解决这个问题,我在'//----------------'注释之间添加了代码。但它似乎没有用。起初它似乎在某种意义上起作用,它在 2 或 3 秒内刷新所有日志(即使重复日志在此期间多次出现)并且当满足 if 语句时甚至此功能消失。最后chrome把所有的记忆都吃光了然后就卡住了。(虽然我不明白为什么它开始占用这么多内存)

如何让我的函数每 6 秒只执行一次,这样才不会浪费计算能力?

问题是 p5.js 在每一帧上都执行了绘制函数。您应该将 setInterval 逻辑移出到设置方法中。它会计算颜色并将其分配给变量。在 draw 方法中使用该变量绘制背景。

setInterval 接受一个函数和一个时间间隔作为参数。如果可能,浏览器将每 t 毫秒调用一次传递的函数。但是,如果浏览器太忙,将无法在准确的预定时间调用它。

当你有太多的 setIntervals 工作时,你的浏览器很快就会被它们淹没。当您不再需要定期执行某个函数时,您可以通过 clearInterval 摆脱它,例如:

var currentInterval;
function draw() {
    if (currentInterval) clearInterval(currentInterval);
    currentInterval = setInterval(function() {
        //...
    }, 6000);
}