There are 2 mainly tie function:
1. setTimeout( call back function, waittime)
When the time equal to waittime you set, the callback function will be activated
the unit of wait time is ns, it means if you want to set waittime as 2 seconds, you should fill waittime = 2000
2. setInterval(callback function, waittime)
The function count time gradually, then call callback function each time the time count eqaul to waittime
function percent(p)
var waitTime = 3000;
var currentTime = 0;
var waitInterval = 10;
var percentWaited = 0;
function writeWaitingPercent(p) {
process.stdout.clearLine();
process.stdout.cursorTo(0);
process.stdout.write(`waiting ... ${p}%`);
}
var interval = setInterval(function() {
currentTime += waitInterval;
percentWaited = Math.floor((currentTime/waitTime) * 100);
writeWaitingPercent(percentWaited);
}, waitInterval);
setTimeout(function() {
clearInterval(interval);
writeWaitingPercent(100);
console.log("\n\n done \n\n");
}, waitTime);
process.stdout.write("\n\n");
writeWaitingPercent(percentWaited);
Try it, bro!!

本文深入解析JavaScript中的两种主要定时器功能:setTimeout与setInterval。详细介绍了它们的工作原理、使用场景及如何通过它们实现进度显示效果。
972

被折叠的 条评论
为什么被折叠?



