How can I maintain the consistent speed of the Javascript timer even when the .deck is clicked?

Currently, I'm working on creating a memory card game. In this game, the deck of cards is represented by the class .deck. Strangely enough, every time I click on a card, the timer starts to speed up instead of keeping a consistent pace. How can I tackle this issue and prevent the timer from accelerating?

function startTimer() { 
    $(".deck").on("click", function () {
        nowTime = setInterval(function () {
            $timer.text(`${second}`)
            second = second + 1
        }, 1000);
    });
}

Answer №1

Instead of initiating multiple intervals every time someone clicks, it would be more efficient to start just one interval. If you only want the timer to start when the first card is clicked:

function startTimer() {
    // It's a good practice to remove any existing timers before starting a new one
    // You might have a function called "stopTimer" that clears the interval.
    clearInterval(nowTime);

    let hasStarted = false;
    $(".deck").on("click", function () {
        if (hasStarted) return;

        nowTime = setInterval(function () {
            $timer.text(`${seconds}`);
            seconds++;
        }, 1000);
        hasStarted = true;
    });
}

However, there are some improvements that can be made to this code. Otherwise, you will accumulate many unused event listeners.

(Additionally, I personally believe that using jQuery should be avoided.)

Answer №2

In order to ensure accurate timing, it is important to stop the previous timer before starting a new one. Failing to do so can result in multiple timer callback functions executing consecutively, giving the false impression that the timer is speeding up.

function initiateTimer() { 
  $(".cards").on("click", function () {
    clearInterval(timer); // Stop previous timer

    timer = setInterval(function () {
      $timerText.text(`${seconds}`);
      seconds++;
    }, 1000);
  });
}

Another approach to tackling this issue is by allowing the click event callback to run only during the initial button click:

function initiateTimer() { 
  $(".cards").on("click", countdown);

  function countdown() {
    timer = setInterval(function () {
      $timerText.text(`${seconds}`);
      seconds++;
    }, 1000);
    $(".cards").off("click", countdown); // Remove the click event handler
  }
}

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

Retrieving parameter values from href using jQuery

Script <a href="#?cat=MT&typ=1" data-reveal-id="reveal_popup" onclick="pop();" data-closeonbackgroundclick="false" data-dismissmodalclass="close-reveal-modal">due today</a> <a href="#?cat=MT&typ=2" data-reveal-id="reveal_popup" on ...

The functionality of Jquery-chosen appears to be malfunctioning when applied to a select element

I am encountering an unusual issue with Jquery-Chosen. There is a multi-select box within a pop-up where the options are populated using an ajax call. Strangely, Jquery-Chosen does not seem to work on it. However, if I use a static multi-select box in the ...

The cloned rows created with jQuery are failing to submit via the post method

Hello, I am currently working on a project in Django and could use some assistance with my JavaScript code. Specifically, I am trying to incorporate a button that adds new rows of inputs. The button does function properly as it clones the previous row usin ...

Transfer Data from a Factory to a Controller in AngularJS

Although it may seem like a simple question, it has taken me nearly 3 hours to try and figure out what went wrong here. Perhaps someone could help identify the issue and provide a solution (it seems like an easy fix, but I'm just not seeing it). So, h ...

Retrieve all attributes of an element with the help of jQuery

I am attempting to extract all the attributes of an element and display their names and values. For instance, an img tag may have multiple unknown attributes that I need to access. My initial idea is as follows: $(this).attr().each(function(index, element ...

Modifying CSS using jQuery in a PHP While Loop

I've been racking my brain trying to solve this issue, experimenting with different approaches but so far, no luck. Question: How can I dynamically change the color of a specific div within a PHP while loop using jQuery after receiving an AJAX respon ...

A tool that showcases outcomes determined by the interaction of two variables

I have two select inputs: <select id="inputA"> <option>1</option> <option>2</option> <option>3</option> </select> <select id="inputB"> <option>1</option> <option>2</opti ...

What is the best way to add content to a box once it has been hovered over?

Looking to create a sticky note-style design, but struggling with displaying the content inside the box only when hovered. In my code example below, can you help me achieve this effect? body { margin: 45px; } .box { display:inline-block; backgrou ...

Struggling to Personalize Kendo Calendar Month templates using Knockout Kendo JS Binding

I have made modifications to the Kendo Calendar Month Template Resource which can be found Here without utilizing knockout-kendo.js. The official Kendo Reference is available Here. The issue arises when I implement the following code in knockout-kendo.js ...

Creating a highly innovative server infrastructure tailored for Dojo applications with exceptional features

Recently, I have been using web2py for my projects and have found it incredibly useful in creating RESTful web applications. However, I am now looking to expand my skills in JavaScript by developing a more modern and dynamic client-side application that re ...

jQuery if statement appears to be malfunctioning

When the condition operates alone, everything works fine. However, when I introduce an 'and' operation, it does not function correctly. If only one of them is true, the code works. It also successfully takes input values. <!DOCTYPE HTML Code ...

Determine the most recent API response and disregard any outdated responses from previous calls

I am currently working on a search page where the user can input text into a search box. With each character they enter, an ajax call is made to update the UI. However, I am facing an issue in determining the response from the last API call. For example, i ...

Only wrap certain elements if they consist of two specific items

<div class="section"> <label>Title: </label> <input type="text" /> </div> <div class="section"> <label>Text: </label> </div> My goal is to enclose the label + input within an additional div ...

Express JS causing NodeJS error | "Issue with setting headers: Unable to set headers after they have been sent to the client"

As I embark on my journey to learn the fundamentals of API development, I am following a tutorial on YouTube by Ania Kubow. The tutorial utilizes three JavaScript libraries: ExpressJS, Cheerio, and Axios. While I have been able to grasp the concepts being ...

Looking for a checkbox change event that can detect and respond to changes in the checked state made programmatically

(jQuery 1.4.4) I am facing an issue with a checkbox where the .change() listener works well when the user manually clicks on the checkbox. However, I also require it to trigger when I programmatically change the status of the checkbox in jQuery using .at ...

Retrieve outcome from successful AJAX post and update HTML using globalEval

I have a function in JQuery that asynchronously posts data function post_data_async_globalEval(post_url, post_data, globaleval) { $.ajax({ type: 'POST', url: post_url, data: post_data, dataType: 'html', async: true, ...

Utilizing the CSS 'overflow: hidden' property and jQuery to restrict users from scrolling during a loading page

OBJECTIVE I aim to restrict the user from scrolling while the page is loading. ISSUE The snippet of code provided successfully prevents the user from scrolling during the additional 2 seconds of the loader animation: $('body').toggleClass(&ap ...

Unable to save or create files in Store.js

Recently, I've been trying to save a file on client storage using Store.js. After changing the date with store.set and logging it to the console successfully, I encountered an issue where the data was not being saved in the app directory as expected. ...

Tips for choosing the remaining items in a multiple selection process

In my HTML form, I have a multi-select field that contains categories and the corresponding items within each category. My goal is to allow users to select individual courses or select an entire category (identified by values starting with "cat_") in orde ...

Determine the minimum and maximum width of jQuery UI resizable during the "resizestart" event

As a newcomer to Javascript, I am facing challenges navigating my way around. Currently, I am attempting to create a jQuery plugin that will facilitate resizing elements using the jQuery UI resizable plugin. My goal is to implement logic that dynamically ...