Learn nodejs, Global timing functions

In the last lesson we started working with Node.js asynchronously by using event listeners. Another way we can work with Node.js asynchronously is through using the timing functions. The timing functions setTimeout, clearTimeout, setInterval, and clearInterval work the same way they do in the browser and are available to you globally.

Let’s go ahead and use a setTimeout function. Let’s navigate to our Exercise Files. In the start folder you will find an empty JavaScript file called timers.js. Let’s go ahead and open that up in Sublime. And in this file I’m going to create a variable for a waitTime, and we will make the waitTime three seconds long.

And then I’m going to go ahead and console.log a Wait for it message. And what we’re also going to do is use our timing function setTimeout. So a setTimeout will create a delay of a certain time and then invoke a callback function. So what we’re going to do is invoke this function after our delay. And our delay is our waitTime, or three seconds. So times are handled in milliseconds, which is why 3000 milliseconds will equal three seconds.

What we’re going to do is cause a timeout that will cause this application to wait for three seconds and then it will invoke this callback function where we will simply console.log a done. So during these three seconds while we’re waiting our application is going to be running. Let’s go ahead and go to the Terminal and test this out. So I will node timers our timers.js file. And what we see is Wait for it. And after about three seconds we see done and we are back out to our Terminal prompt.

So after three seconds the application exits, which means that during that time the application is running. Let’s go back to our code and take a look at setInterval. So what I’m going to do is also add an interval to this. We will add a couple more variables right here under our waitTime. I’m going to add a variable for the currentTime, which when we start this application will be 0 milliseconds. And then I’m also going to add a variable for the waitInterval. The waitInterval is going to be half a second.

And what this means is I want to fire this interval callback function like a heartbeat, every half second. So setTimeout waits for a delay once and then invokes the callback function, where setInterval will fire the callback function over and over again on an interval time. So let me add a setInterval to my code. So what we’re going to do every half second is one, we need to update our current time, so we want to add the waitInterval to the current Time.

So this will add 500 milliseconds to the currentTime every 500 milliseconds. That means our currentTime will give us an accurate indicator of how long we’ve waiting. Now let’s go ahead and log a message to the console using a string template. So that means we want to use those “. And I will log waiting. And I can use the $ and the {} in my string template to display a variable, currentTime. And I’m going to divide this by 1000, so we get this currentTime in seconds, so our currentTime is stored in milliseconds, dividing it by 1000 should give us the currentTime is seconds.

And I’d better make sure I put that on the inside of this ` here, there we go. So now we are going to wait three seconds and log done, but then every half second during the waiting we’re going to log how long we’ve been waiting. Let’s go ahead and save this and navigate to the Terminal. And I’m going to run this file through node timers. And as you can see, Wait for it, and every half second we see the message. Notice that after the done log we are still going. That interval is like a heartbeat, it will not stop.

Every half second it’s going to let us know how long we’ve been waiting. And as long as that interval is running our application is running. So we could literally sit here and watch this timer time forever. In order to stop this application though we’re going to hit control C. And what we need to do is after three seconds we need to stop our interval from running. So let’s go back to our code. The clearTimeout and clearInterval functions are used to stop intervals or stop any timeouts that we might have currently in our application. So after three seconds, just before we’re done, we need to clear this interval.

So the way that we can clear an interval is we first need to set a variable instance to that interval. So on line 7 if I say var interval = setInterval now I have this interval instance saved to the variable. I can use that interval variable in a clearInterval. So clearInterval and then send it, the interval that we would like to clear will stop this interval from running. So it will stop that heartbeat from displaying that message on the page. And when there is no longer an interval running we will also exit the application, because we no longer have any listeners and we also no longer have any intervals.

Let’s go ahead and save this and see what happens. So we can go back out to the Terminal and I will clear these old messages by typing clear, cls on a PC. And now let’s go ahead and node timers and now we can see we are waiting for it, but after three seconds when we are done we are actually going to display the done and the application stops. Let’s take one more iteration on this code to display the time waiting in a percentage and also control the standard output, so that we overwrite the last line, meaning that we can see a percentage number grow.

Let’s go ahead and go back to our code. And the first thing that we’re going to do is we are going to add a function for writing the percentage. So here on line 5 I’m going to delete this console.log that says Wait for it, and I’m going to add a function. And this function I’m going to use for writeWaitingPercent. And we will send it, that waiting percentage, as an argument. and then what we’re going to do this time is we’re going to use the process standard output object to clear the last line that we wrote.

The clearLine function on standard output will clear the last line inside of the Terminal. And then I’m going to move the cursor back to the start of that line using the standard output object. cursorTo object will move our cursor back to the beginning of that line. Now I’m going to use the process.stdout object to write the percentage that we’ve been waiting. And I can, again, use a string template for this one, since we’re going to use a variable. And I will write waiting…

And now we can actually use that percentage variable right here. So if you send this writeWaitingPercent function a percentage it will write it over the last line in the Terminal. So now I’m going to add a variable to hold the percentage that we’ve been waiting. And I will call this variable percentWaited. And we will start that out as 0 as well. So the very first thing I want to do after we set up these intervals and after we set up the timeout is I want to write that to the console, so I’m going to use my function writeWaitingPercent and I’m going to send it the percentWaited, which should start out as zero.

So when we start this application we should see that we’ve been waiting 0%. Right before we write that waiting percentage let’s go ahead and add a couple new lines, process.stdout.write and we can go ahead and add a couple new lines there. There we go. Now in the setTimeout once we are totally finished with this application, after we clear the interval, let’s go ahead and write the WaitingPercent as 100. So when we’re done we will see that we have waited for 100% of the time.

Now what we want to do is calculate the percent waited inside of the interval. So inside of this interval on line 13, right after we append the currentTime, what we’re going to do is calculate that percentWaited. So I am going to say percentWaited is going to be = to Math.floor. This is JavaScript, so we have available to us the Math object on the top level, and what we’re going to do is take the currentTime and divide it by the waitTime, so the waitTime is our total time, the currentTime is the amount of time that we’ve waited, we can divide the currentTime by the waitTime and multiple that by 100, and we will get a percentage.

So now instead of writing this message to the console, what we’re going to do is let our writeWaitingPercent function do that for us. So I will call writeWaitingPercent and we will add the percentWaited. Alright. So now we’ve added the ability to show our users how long they’re waiting as a percentage. Let’s go ahead and save this and go back out to the Terminal. And again, we can clear our previous Terminal screen with clear, or cls on a PC.

And now I’m going to run our timers file and we can see that we are waiting and then eventually when we get to 100 we are done. So there are just a couple more things that we want to add to this just to clean it up. It appears to be working, but our users do not know those are percentages, unless we throw a little % indicator in there. And the last thing is is before we log done we also probably want to log a couple of new lines and maybe just a couple of new lines after it to make it look good. There we go.

So let’s go ahead and save this and try to run it one last time. Go back out to our Terminal, and we will node timers, and now we can see that our percentWaiting is being up. If we want to see that number go faster, if we want to see that waiting percentage be calculated faster all we need to do is up our waitInterval. So I’m going to go back to the application, I will change our waitInterval to 10 milliseconds instead of 500, meaning our waitInterval is now going to fire 10 times a second instead of twice a second.

So let’s go ahead and save this and go back out to our Terminal. And I will clear this. And let’s run it one last time, node timers, and we can see that percentage is being calculated 10 times a second. So those are the timing functions. They’re available to you globally in Node.js and they work the exact same way that they would work in the browser.

Leave a Reply

avatar
1000
  Subscribe  
Notify of