count 函数
每次调用一个函数主动加 1
count() 1
count() 2
count() 3
var count = (function () {
var a = 0
return function () {console.log(++a)
}
})()
count() // 1
count() // 2
count() // 3
sleep 睡眠函数
比方 sleep(1000) 代表期待 1000ms
办法一:ES5 形式实现
function sleep(callback, time) {if (typeof callback == 'function') {setTimeout(callback, time)
}
}
function output() {console.log(111)
}
sleep(output, 2000)
办法二:应用 promise 形式
const sleep = (time) => {return new Promise((resolve) => {setTimeout(resolve, time)
})
}
sleep(2000).then(() => {console.log(111)
})
办法三:利用 async
function sleep(ms) {return new Promise((resolve) => {setTimeout(resolve, ms)
})
}
async function init() {var temp = await sleep(2000)
console.log(111) //2s 后执行
}
init()