Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
jQuery HOTSHOT

You're reading from   jQuery HOTSHOT Ten practical projects that exercise your skill, build your confidence, and help you master jQuery

Arrow left icon
Product type Paperback
Published in Mar 2013
Publisher Packt
ISBN-13 9781849519106
Length 296 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Dan Wellman Dan Wellman
Author Profile Icon Dan Wellman
Dan Wellman
Arrow right icon
View More author details
Toc

Table of Contents (18) Chapters Close

jQuery HOTSHOT
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
1. Sliding Puzzle FREE CHAPTER 2. A Fixed Position Sidebar with Animated Scrolling 3. An Interactive Google Map 4. A jQuery Mobile Single-page App 5. jQuery File Uploader 6. Extending Chrome with jQuery 7. Build Your Own jQuery 8. Infinite Scrolling with jQuery 9. A jQuery Heat Map 10. A Sortable, Paged Table with Knockout.js Index

Starting and stopping the timer


At this point, our game is fully functional and the puzzle can be unscrambled; however to make it more fun we should introduce an element of competitiveness by incorporating a timer.

Prepare for Lift Off

In this task we'll need to complete the following steps:

  • Check the timer isn't already running when the Start button is clicked

  • Start the timer from 0

  • Increment the timer every second

  • Update the display on the page so that the player can see how long the current game has taken so far

Engage Thrusters

To check whether the timer is already running when the Start button is clicked we should add the following code directly after where we appended the shuffled pieces to the page, and directly before the call to draggable():

pieces.appendTo(imgContainer).draggable("destroy");

if (timer) {
    clearInterval(timer);
    timerDisplay.text("00:00:00");
}

timer = setInterval(updateTime, 1000);
currentTime.seconds = 0;
currentTime.minutes = 0;
currentTime.hours = 0;

pieces.draggable({

Next we can add the function that increments the timer and updates the display. This code should come directly after where we update currentTime.hours in the previous code:

function updateTime() {
  
    if (currentTime.hours === 23 && currentTime.minutes === 59 &&
currentTime.seconds === 59) {
        clearInterval(timer);          
    } else if (currentTime.minutes === 59 && currentTime.seconds === 59) {

        currentTime.hours++;
        currentTime.minutes = 0;
        currentTime.seconds = 0;
    } else if (currentTime.seconds === 59) {
        currentTime.minutes++;
        currentTime.seconds = 0;
    } else {
        currentTime.seconds++;
    }

    newHours = (currentTime.hours <= 9) ? "0" + currentTime.hours :

    currentTime.hours;
    newMins = (currentTime.minutes <= 9) ? "0" + currentTime.minutes :

    currentTime.minutes;
    newSecs = (currentTime.seconds <= 9) ? "0" + currentTime.seconds : 

    currentTime.seconds;

    timerDisplay.text([
        newHours, ":", newMins, ":", newSecs
    ].join(""));


}

Objective Complete - Mini Debriefing

The first thing we have to do in this task is check whether a timer is already running. The timer will be stored in one of our "global" variables so we can check it easily. We use an if statement to check whether timer contains a truthy value (see the previous information on JavaScript's truthy and falsey values).

If it does, we know the timer is already running, so we cancel the timer using JavaScript's clearInterval() function, passing in our timer variable as the timer to clear. We can also reset the timer display if the timer is already running. We selected the timer display element from the page and cached it when we initially declared our variables at the start of this project.

Next we start the timer using JavaScript's setInterval() method and assign it to our timer variable. When the timer begins this variable will contain the ID of the timer, not the value of the timer, which is how clearInterval() knows which timer to clear.

The setInterval() function accepts a function to execute after the specified interval as the first argument, and the interval as the second argument. We specify 1000 milliseconds as the interval, which is equal to 1 second, so the function passed as the first argument will be called every second until the timer is cleared.

Once the timer has started we can also reset the values stored in the object we'll use to keep track of the timer – the currentTime object. We set the seconds, minutes, and hours properties of this object to 0. We need an object to keep track of the time because the timer variable itself just contains the ID of the timer.

Next we added the updateTime() function that will be called by our interval every second. All we do in this function is update the relevant properties of the currentTime object, and update the display. We use an if conditional to check which parts of the timer to update.

We first check that the timer has not reached 24 hours. I would hope that no one would actually spend that long playing the game, but if the browser is left open for some reason for this length of time, we don't want the time display to say, for example, 24 hours and 1 minute, because at that point, we really should update the display to say 1 day, 0 hours, and 1 minute. But we aren't bothering with days so instead we just stop the timer.

If the timer has not reached this length of time we then check whether the current minutes equal 59 and the current seconds equal 59. If they do we need to increment currentTime.hours by 1 and reset the currentTime.minutes and currentTime.seconds properties back to 0.

If this check fails we then check whether the seconds equal 59. If they do, we increment the currentTime.minutes property and then reset currentTime.seconds back to 0. If this second test also fails we know that all we have to do is increment currentTime.seconds.

Next we need to check whether we need to pad any of the time components with a leading 0. We could use another if else conditional for this, but the JavaScript ternary construct is neater and more compact so we use this instead.

First we test whether currentTime.hours is equal to or less than 9 and if so we add 0 to the start of the value. We do the same for currentTime.minutes and currentTime.seconds.

Finally, we build the string which we will use to update the timer display. Instead of using boring and slow string concatenation, we again use an awesome array comprising the various parts of the display and then join the array.

The resulting string is set as the value of the <span> element contained in the timerDisplay variable and the element on the page is updated using jQuery's text() method.

At this point we can now click on the button to shuffle the puzzle pieces, and watch as the timer starts to increment.

You have been reading a chapter from
jQuery HOTSHOT
Published in: Mar 2013
Publisher: Packt
ISBN-13: 9781849519106
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image