JavaScript setTimeout()在负载很重的情况下变慢

cor*_*ore 5 javascript settimeout

我创建了一个淡化元素背景颜色的脚本.我使用setTimeout()每5毫秒对颜色进行一次增量更改.如果我只是一次淡化一件事的背景颜色,那么该脚本效果很好,但如果我有50个元素,我一下子都褪色,速度比5毫秒慢得多,因为所有并发setTimeout()一次运行.例如,如果我一次褪色50个元素,通常应该在1秒内执行的淡入淡出可能需要30秒.

我有什么想法可以克服这个问题?

这是脚本,以防任何人有想法:

function fadeBackground(elementId, start, end, time) {
    var iterations = Math.round(time / 5);

    var step = new Array(3);

    step[0] = (end[0] - start[0]) / iterations;
    step[1] = (end[1] - start[1]) / iterations;
    step[2] = (end[2] - start[2]) / iterations;

    stepFade(elementId, start, step, end, iterations);
}

function stepFade(elementId, cur, step, end, iterationsLeft) {
    iterationsLeft--;

    document.getElementById(elementId).style.backgroundColor
        = "rgb(" + cur[0] + "," + cur[1] + "," + cur[2] + ")";

    cur[0] = Math.round(end[0] - step[0] * iterationsLeft);
    cur[1] = Math.round(end[1] - step[1] * iterationsLeft);
    cur[2] = Math.round(end[2] - step[2] * iterationsLeft);

    if (iterationsLeft > 1) {
        setTimeout(function() {
            stepFade(elementId, cur, step, end, iterationsLeft);
        }, 5);
    }
    else {
        document.getElementById(elementId).style.backgroundColor 
            = "rgb(" + end[0] + "," + end[1] + "," + end[2] + ")";
    }
}
Run Code Online (Sandbox Code Playgroud)

它的使用方式如下:

fadeBackground("myList", [98,180,232], [255,255,255], 1000);
Run Code Online (Sandbox Code Playgroud)

Bri*_*say 11

以下是Google撰写的一篇文章,作者讨论了他们关于Gmail定时器的工作.他们发现,使用单个高频定时器比使用多个定时器更快,如果它们使用了大量且快速的定时器.

您可以使用一个每5ms触发一次的计时器,并将需要淡化的所有元素添加到跟踪它们在淡入淡出过程中的位置的数据结构中.然后,您的一个计时器可以查看该列表,并在每次触发时为每个元素执行下一个淡入淡出.

另一方面,您是否尝试使用MootoolsJQuery等库而不是滚动自己的动画框架?他们的开发人员在优化这些类型的操作方面投入了大量的精力.