Skip to content

Instantly share code, notes, and snippets.

@mnyamor
Last active October 27, 2016 23:16
Show Gist options
  • Save mnyamor/cf947c270352c977dc5a529a041cb95a to your computer and use it in GitHub Desktop.
Save mnyamor/cf947c270352c977dc5a529a041cb95a to your computer and use it in GitHub Desktop.
Global timing functions - setInterval
/*
Working with Node.js asynchronously through the use of timing functions.
The timing functions are:- setTimeout, clearTimeout, setInterval, and clearInterval
- setTimeout will create a delay of a certain time and then invoke a callback function
- setInterval will not stop, its like a heartbeat
- clearInterval & clearTimeout will stop intervals or timeouts that are currently running.
*/
var waitTime = 3000; //waitTime is our total time
var currentTime = 0; //currentTime is the amount of time that we've waited
var waitInterval = 10; //half a sec
var waitingPercentage = 500; // variable to hold the percentage that we've been waiting.
console.log('wait for it');
//func to show our users how long they're waiting as a percentage.
function writeWaitingPercent(p) {
// The clearLine function on standard output will clear the last line inside of the Terminal.
process.stdout.clearLine();
//cursorTo object will move our cursor back to the beginning of that line.
process.stdout.cursorTo(0);
//process.stdout object to write the percentage that we've been waiting
process.stdout.write(`waiting ... ${p}%`);
}
//fire interval function like a heartbeat every half second
//interval instance
var interval = setInterval(function(argument) {
//update current time (we get accurate indicator of how long we've been waiting).
currentTime += waitInterval;
//calculate the percent waited inside of the interval.
percentWaited = Math.floor((currentTime/waitTime) * 100);
writeWaitingPercent(percentWaited);
//console.log(`waiting ${currentTime/1000} seconds...`);
}, waitInterval);
setTimeout(function() {
// this will stop the interval from running. It will also exit the application when there is no more running instances.
clearInterval(interval);
//use writeWaitingPercent func and send it the percentWaited, which should start out as zero.
//after we clear the interval, when we're done we will see that we have waited for 100% of the time.
writeWaitingPercent(100);
console.log("\n\n done \n\n");
}, waitTime);
process.stdout.write("\n\n");
writeWaitingPercent(percentWaited);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment