前言:從《原生JS實現(xiàn)輪播(上)》中JS實現(xiàn)漸變效果,引出的setTimeout
用法問題沫浆。
對于setInterval
比較熟悉葡公,但對于setTimeout
极颓,因為用得少,不夠了解近零,總覺得有一層神秘的面紗待揭開。
1.setTimeout
實現(xiàn)setInterval
效果
showTime();
function showTime(){
var today = new Date();
document.write("The time is: " + today.toString());
document.write("<br />");
setTimeout("showTime()", 5000); //調(diào)用自身
}
和setInterval
的區(qū)別?這個還待深究顾孽。
2.JavaScript引擎單線程
瀏覽器多線程/循環(huán)阻塞/事件循環(huán)模型(這幾個概念待了解)
問題:
<script type="text/javascript">
var start = new Date;
setTimeout(function(){
var end = new Date;
console.log('Time elapsed:', end - start, 'ms');
}, 500);
while (new Date - start < 1000) {};
</script>
輸出的結(jié)果并不是期望的Time elapsed: 500 ms
,而是大于1000ms的比规。因為JS是單線程的若厚,while完成后(執(zhí)行了1000ms),達(dá)到了執(zhí)行setTimeout的條件了才執(zhí)行蜒什。也就是說测秸,對setTimeout中匿名函數(shù)的實際調(diào)用被while()循環(huán)阻塞了,實際的調(diào)用在while()循環(huán)阻塞結(jié)束后才真正執(zhí)行灾常。
3.延遲時間為0
<script>
console.log('a');
setTimeout(function(){
console.log('b');
},0);
console.log('c');
console.log('d');
</script>
顯示的結(jié)果是:acdb霎冯,因為即使延遲時間為0,瀏覽器也是有默認(rèn)最小的延遲時間的钞瀑,如HTML5定義的最小時間間隔是4毫秒沈撞。即使我們把setTimeout的毫秒數(shù)設(shè)置為0,被調(diào)用的程序也不會馬上啟動雕什。
4.setTimeout
實現(xiàn)動畫
例子:
<div id="container" style="width:100px;height:100px;border:1px solid black;"></div>
<div id="btn" style="width:40px;height:40px;line-height:40px;margin-top:20px;background:pink;">click</div>
<script>
window.onload = function(){
var con = document.getElementById('container');
var btn = document.getElementById('btn');
//Params: i 為起始高度缠俺,num為預(yù)期高度
function render(i, num) {
i++;
con.style.height = i + 'px';
//亮點在此
if(i < num){
setTimeout(function() {
render(i, num); //這里調(diào)用自身而循環(huán)執(zhí)行
},0);
}
else {
con = null;
btn = null;
}
};
btn.onclick = function(){
render(100, 200);
};
};
</script>
5.setTimeout
實現(xiàn)捕獲事件
例子(捕獲事件又給自己挖了個坑)
<div id="parent" style="width:100px;height:100px;border:1px solid black;">
<div id="child" style="width:50px; height:50px; background-color:#fcc;"></div>
</div>
<script>
//點擊子元素,實現(xiàn)子元素的事件在父元素觸發(fā)后觸發(fā)
window.onload = function(){
var parent = document.getElementById('parent');
var child = document.getElementById('child');
parent.onclick = function(){
console.log('parent');
}
child.onclick = function(){
//利用setTimeout贷岸,冒泡結(jié)束后壹士,最后輸出child
setTimeout(function(){
console.log('child');
},0);
}
parent = null; //不知為何這句無效
child = null; //不知為何這句無效
}
</script>
6.setTimeout
中的this
這個等研究this
的時候一起,又挖了個坑凰盔。墓卦。
參考文章
http://www.cnblogs.com/giggle/p/5346531.html
http://www.cnblogs.com/Medeor/p/4945687.html