Incorporating a timer feature into the code for my memory game

Seeking the optimal method to incorporate a timer into my memory game. This game comprises numerous squares, and when the user successfully completes it, a modal appears congratulating them on their win and providing an option to restart the game.

The objective is to display the time taken by the user to play the game, starting from 0 seconds upon opening the page until x seconds elapse. Upon completion of the game, the score is displayed in the modal for the user's reference. However, if the user fails to complete the quiz within x seconds, a function triggers the modal to inform them they have run out of time and offers a chance to restart.

I am utilizing a modified version of this game on CodePen

HTML:

<div class="modal-overlay">
    <div class="modal">
        <h2 class="winner">Congratulations!</h2>
        <button class="restart">Play Again?</button>
        <p class="message">Created on <a href="http://codepen.io">CodePen</a> by <a href="http://codepen.io/natewiley">Nate Wiley</a></p>
        <p class="share-text">Share it?</p>
        <ul class="social">
            <li><a target="_blank" class="twitter" href="http://twitter.com/share?url=http://codepen.io/natewiley/pen/HBrbL"><span class="brandico-twitter-bird"></span></a></li>
            <li><a target="_blank" class="facebook" href="http://www.facebook.com/sharer.php?u=http://codepen.io/natewiley/pen/HBrbL"><span class="brandico-facebook"></span></a></li>
            <li><a target="_blank" class="google" href="https://plus.google.com/share?url=http://codepen.io/natewiley/pen/HBrbL"><span class="brandico-googleplus-rect"></span></a></li>
        </ul>
    </div>
</div>

All logos are properties of respective owners, no intention of Copyright infringement.

CSS section:

@import url(http://weloveiconfonts.com/api/?family=brandico);

/* brandico */
[class*="brandico-"]:before { font-family: 'brandico', sans-serif; }

* { box-sizing: border-box; }
... (CSS code continues)
...

Javascript:

(function(){

var Memory = {

    init: function(cards){
        this.$game = $(".game");
        this.$modal = $(".modal");
        ... (Javascript code continues)
... 

Answer №1

To create a timer function, you can utilize either setTimeout in a recursive manner or use setInterval as shown below:

(function () {
  var timeContainer = document.getElementById("timer-value");
  var startButton = document.getElementById("start-game");
  var timer = 0;
  var maxTime = 30;
  var timeout = null;
  function count () {
    timeout = setTimeout(function () {
      if (timer < maxTime) {
        timer++;
        timeContainer.innerText = timer;
        count();
      }
      else {
        alert("Time's up!");
        startButton.style.display = "inline-block";
      }
    }, 1000);
  }
  function endGame () {
    clearTimeout(timeout);
    startButton.style.display = "inline-block";
    alert("You completed the game within the given time frame!");
  }
  function startGame () {
    if (timeout) { clearTimeout(timeout); }
    timer = 0;
    timeContainer.innerText = timer;
    this.style.display = "none";
    count();
  }
  document.getElementById("start-game").addEventListener("click", startGame);
  document.getElementById("end-game").addEventListener("click", endGame);
})();
<h3>Timer: <span id="timer-value">0</span></h3>
<button id="start-game">Start Game</button> <button id="end-game">End Game</button>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unlock the potential of HTML5 Datalist: A comprehensive guide on integrating it with

The latest version of HTML, HTML5, has introduced a new tag called datalist. This tag, when connected to <input list="datalistID">, allows for autocomplete functionality on web forms. Now the question arises - what is the most efficient approach to ...

Custom container width causes animation to crash when scrolling

I'm having trouble with my header. When the containers change with scrolling, an animation takes place. Everything works fine with native Bootstrap CSS, but when I customize the width of the container in my custom CSS (the width set to 1140px), the an ...

Keeping JSP current with changes made to files on the client side

Currently, I am tackling a project that consists of two main components: a) A Java Application that runs on a client machine. b) A Web Application that is hosted on a web server. The Java Application generates results at random intervals. These results n ...

What is the process for creating a new Object based on an interface in Typescript?

I am dealing with an interface that looks like this: interface Response { items: { productId: string; productName: string; price: number; }[] } interface APIResponse { items: { productId: string; produc ...

Material Design - The element provided is not valid: it should be a string for built-in components or a class/function for composite components, but instead it is an object

How are you today? I am currently working on a React project using Webpack and Babel. I encountered an issue when trying to incorporate Material UI components from https://mui.com/. Whenever I import a MUI component into my project, I receive the followin ...

Guide to automatically updating a table with AJAX requests

My task involves utilizing AJAX to request a random string consisting of 10 numbers from an asp page. The numbers must be delimited by "||" and displayed in a table format. The table is designed to showcase only the top 10 results, with each new row addin ...

IE does not support hover effects

Having trouble with a hover effect that works in Chrome but not in MSIE. Are there any alternatives or fixes to make it work in MSIE? The hover/rollover effects I've tried all seem to have this issue in IE. normalize.css demo.css set2.css font- ...

Steps for deactivating tab stops on the primary webpage in the presence of a snackbar

On my web page, there are multiple drop-down menus, input fields, and buttons that can be interacted with using both the tab key and mouse. After entering certain data, I trigger a snackbar (source: https://www.w3schools.com/howto/howto_js_snackbar.asp) t ...

Encountering ExpressionChangedAfterItHasBeenCheckedError during ngOnInit when utilizing Promise

I have a simple goal that I am working on: I want to display data obtained from a service in my component. This is how it used to work: In my component: ... dataSet: String[]; ngOnInit(){ this._service.getDataId().then(data => this.dataSet = da ...

Developers specializing in Google Maps navigate to a particular destination

I have been working on an app that provides users with the best options for places to visit, utilizing Google Maps technology. Here is what I have accomplished so far: Show the user their current location Show the user possible destinations (with marker ...

What is the most effective method for updating a className in Next.js using CSS Modules when a button is activated?

Looking to create a responsive navigation bar that transforms based on screen size? When the width reaches 600px, I'd like to hide the links and instead show a clickable nav button that reveals those options. Upon inspecting my list elements in the c ...

What steps should I take to address the numerous errors I am encountering in Atom using the Atom linter tool?

My Atom interface is showing the following errors: {Error running gjslint}(x4) {Error running selective}(x4) Upon checking the errors section, I found the following details: [Linter] Error running selective Error: ENOENT: no such file or directory, open ...

Is there a way to resolve the scrolling problem on Google Maps?

When using the Google Maps V3 API, an issue arises where zooming out on the map using the scrollbar also causes the page to scroll along with it. This can be quite frustrating and so far I have not been able to find a way to disable this scrolling behavi ...

Displaying tooltips dynamically for newly added elements all sharing a common class in React

I'm facing an issue with the primereact tooltip component from . Everything seems to be working fine except for the target property. When I have multiple elements on a page with the same class, the tooltip works as expected. However, when I add a new ...

Can the text color be customized to match the brightness level of the background area being covered?

Does anyone know of a plugin or method that can automatically change the color of text or swap predefined images/icons based on the average brightness of its parent element's background? If the background is dark, it should make the text white or swit ...

The color of the last clicked DIV is supposed to stay permanent, but for some unknown reason

I'm attempting to replicate this design in my project: http://jsfiddle.net/AYRh6/26/ However, I am facing issues with it and cannot pinpoint the exact problem in the code. I am using code for a toggle effect. Any assistance would be greatly appreciat ...

An error was thrown at line 474 in module.js

After recently installing nodejs on my laptop, I'm struggling to run a js file in the node environment. I attempted using this command: node C:\Program Files\nodejs\file.js, but encountered the following error: module.js:474 thr ...

Steps for activating chromedriver logging using the selenium webdriver

Is there a way to activate the chromedriver's extensive logging features from within the selenium webdriver? Despite discovering the appropriate methods loggingTo and enableVerboseLogging, I am struggling to apply them correctly: require('chrom ...

The size of the array within the object does not align

I've run into a roadblock while attempting to implement the tree hierarchy in D3. Initially, I believed that I had correctly structured the JSON data, but upon inspecting the object using Developer's Tool, a discrepancy caught my eye: https://i. ...

How can we create lists using parentheses specifically with Javascript or jQuery?

I am looking to create a formatted list using <ol> and <ul> tags with parentheses included. (1) List1 (2) List2 (3) List3 (4) List4 The challenge is to achieve this formatting purely with javascript or jQuery, without relying on any external ...