setTimeout
Javascript
執(zhí)行引擎的主線程運(yùn)行的時(shí)候生逸,產(chǎn)生堆(heap)和棧(stack)。程序中代碼依次進(jìn)入棧中等待執(zhí)行且预,當(dāng)調(diào)用setTimeout()
方法時(shí)槽袄,瀏覽器內(nèi)核相應(yīng)模塊開始延時(shí)方法的處理,當(dāng)延時(shí)方法到達(dá)觸發(fā)條件時(shí)辣之,方法被添加到用于回調(diào)的任務(wù)隊(duì)列掰伸,只有執(zhí)行引擎棧中的代碼執(zhí)行完畢,主線程才會(huì)去讀取任務(wù)隊(duì)列怀估,依次執(zhí)行那些滿足觸發(fā)條件的回調(diào)函數(shù)。
如果setTimeout
加入隊(duì)列的阻塞時(shí)間大于兩個(gè)setTimeout
執(zhí)行的間隔時(shí)間合搅,那么先加入任務(wù)隊(duì)列的先執(zhí)行多搀,盡管它里面設(shè)置的時(shí)間比另一個(gè)setTimeout
的要大。
栗子1
Time2
先執(zhí)行灾部,因?yàn)樽枞臅r(shí)間大于兩個(gè)setTimeout
之間的間隔時(shí)間康铭。
//Time2
setTimeout(function () {
console.log(2)
}, 400)
const start = new Date()
for (let i = 0; i < 5000; i++) {
console.log('這里只是模擬一個(gè)耗時(shí)操作')
}
const end = new Date()
console.log('阻塞耗時(shí):' + Number(end - start) + '毫秒')
//Time1
setTimeout(function () {
console.log(3)
}, 300)
栗子2
我們把for
循環(huán)里面的時(shí)間設(shè)置短一點(diǎn):
setTimeout(function () {
console.log(2)
}, 400)
const start = new Date()
for (let i = 0; i < 500; i++) {
console.log('這里只是模擬一個(gè)耗時(shí)操作')
}
const end = new Date()
console.log('阻塞耗時(shí):' + Number(end - start) + '毫秒')
//Time1
setTimeout(function () {
console.log(3)
}, 300)
此時(shí),Time1
先執(zhí)行赌髓,因?yàn)樽枞暮臅r(shí)小于Time1
和Time2
的執(zhí)行間隔時(shí)間100
毫秒从藤。
arguments
擁有一個(gè)length
屬性和若干索引屬性的對(duì)象。
const arrayLike = {
0: 'name',
1: 'age',
2: 'sex',
length: 3
}
調(diào)用數(shù)組方法
如果類數(shù)組想用數(shù)組的方法怎么辦呢锁蠕?我們可以用Function.call
間接調(diào)用:
const arrayLike = {
0: 'name',
1: 'age',
2: 'sex',
length: 3
}
const arrayLike = {
0: 'name',
1: 'age',
2: 'sex',
length: 3
}
console.log(Array.prototype.slice.call(arrayLike))
類數(shù)組轉(zhuǎn)數(shù)組
const arrayLike = {0: 'name', 1: 'age', 2: 'sex', length: 3 }
// 1. slice
Array.prototype.slice.call(arrayLike) // ["name", "age", "sex"]
// 2. splice
Array.prototype.splice.call(arrayLike, 0) // ["name", "age", "sex"]
// 3. ES6 Array.from
Array.from(arrayLike) // ["name", "age", "sex"]
// 4. apply
Array.prototype.concat.apply([], arrayLike)
length屬性
Arguments
對(duì)象的length
屬性夷野,表示實(shí)參的長度,舉個(gè)例子:
function foo(b, c, d){
console.log("實(shí)參的長度為:" + arguments.length)
}
console.log("形參的長度為:" + foo.length)
callee屬性
Arguments
對(duì)象的 callee
屬性荣倾,通過它可以調(diào)用函數(shù)自身悯搔。
function fibonacci(n) {
if(n < 0) {
return false
}
if(n === 0) {
return 0
} else if(n === 1) {
return 1
} else {
return arguments.callee(n - 1) + arguments.callee(n - 2)
}
}
console.log(fibonacci(3))