进度条函数
/**
* 创建浏览器控制台进度条
* @param {number} total - 任务总个数
* @returns {{step: ((function(): ({finished: boolean}))|*)}}
*/
function createProcessBar(total) {
let curr = 0
let finished = false
return {
step: () => {
if (finished) return { finished }
curr++
const percentage = Number((curr / total * 100).toFixed(2))
const percentageStr = percentage > 100 ? '100.00%' : `${percentage.toFixed(2)}%`
const currOnBar = Math.ceil(curr * 100 / total)
const bar = `${''.padEnd(currOnBar, '|')} ${percentageStr} ${''.padEnd(100 - currOnBar, '.')}`
console.clear()
console.log(bar)
if (currOnBar >= 100) {
finished = true
}
return { finished }
}
}
}
使用示例
// usage example
const bar = createProcessBar(100)
const timer = setInterval(() => {
const { finished } = bar.step()
if (finished) {
clearInterval(timer)
}
}, 1000)
输出
![](https://img2023.cnblogs.com/blog/1249006/202311/1249006-20231108144402321-1809379135.png)