var fade = function (node) { var level = 1; var step = function () { var hex = level.toString(16); node.style.backgroundColor = "#FFFF" + hex + hex; if(level < 15) { level += 1; setTimeout(step, 100); } }; setTimeout(step, 100); }; fade(document.body);
定义一个函数,它设置一个DOM节点为黄色,然后把它渐变为白色
Why are there two setTimeouts and what do they mean? -PHP Chinese website Q&A-Why are there two setTimeouts and what do they mean? -PHP Chinese website Q&A
Let’s take a look and learn.
setTimeout只是延时一次, 所以最底下那个,是初始时的延迟,然后执行step函数,然后level还没到15,所以level+1,然后执行setTimeout,然后在level还没达到15之前,一直在调用setTimeout延迟调用step函数,直到最后一次setTimeout执行step时,level=15了,不再执行if条件下的内容~