Issues with Response Time in jQuery Reaction Tests

I recently encountered a couple of challenges while working on a reaction test:

  • Firstly, I wanted to incorporate a random pause (2-5 seconds) after the user clicks on a div.

  • Secondly, I aimed to have the divs appear five times in total, providing the player with 5 attempts.

To address the first issue, I experimented with utilizing the setTimeout function. Additionally, I tried using a 'for' loop to control how many times the div would be displayed for the second problem.

For instance:
    
    for(var i = 1; i < 5; i++) {
        $div.css({
            left: Math.floor(Math.random() * widthMax),
            top: Math.floor(Math.random() * heightMax)
        });
    }

Unfortunately, I was unable to find solutions to these challenges.

You can experiment with it here: http://jsfiddle.net/tghca/7/

Any assistance would be highly valued! Thank you!

Answer №1

Here is an example:

$('div').hide();

$('.start').click(function () {
    $(this).hide();
    $('.hint').hide();
    $('div').show();
    generateDiv();
});

var counter = 0;

function testClick() {
    var docHeight = $(document).height(),
        docWidth = $(document).width(),
        $div = $('#test'),
        divWidth = $div.width(),
        divHeight = $div.height(),
        heightMax = docHeight - divHeight,
        widthMax = docWidth - divWidth;

    $div.hide();
    setTimeout(function () {
        $div.css({
            left: Math.floor(Math.random() * widthMax),
            top: Math.floor(Math.random() * heightMax)
        }).show();
        counter++;
        if (counter < 5) {
            generateDiv();
        }
    }, Math.floor(Math.random() * 3000) + 2000)
}

function generateDiv() {
    $('#test').one('click', testClick);
}

Live Example: Fiddle

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

Creating unique random shapes within a larger shape on a canvas, as shown in the image

I have a parent rectangle and would like to add up to 10 or fewer rectangles on the right-hand side corner of the parent rectangle, as shown in the image below: https://i.sstatic.net/RW9ix.png I attempted to write code to achieve this, but the alignment ...

Script in Powershell for converting multiple .csv files to .html format and managing the conversion process

I need to create a script that can merge the content of various .csv files and output them into a single .html file. The objective is to display all filenames as clickable buttons which, when expanded, will show the corresponding content. However, I am fa ...

Creating a basic image carousel with JavaScript, CSS, and HTML

After running the code, I encountered an issue where the first image displays but then after one second, only a white blank screen appears with no further action. It seems like there may be an error in the JavaScript code. Below is the code that was attemp ...

Issue with Webpack: error message "Cannot read property 'readFile' of undefined" is causing no output files to be generated

When utilizing version webpack > 5, the configuration for my appDevMiddleware.js is as follows: const path = require('path'); const webpack = require('webpack'); const webpackDevMiddleware = require('webpack-dev-middleware' ...

When a specific props element is updated, React Hooks automatically update a corresponding state element

Traditionally, I've relied on componentWillReceiveProps instead of hooks, but now I'm facing the challenge of not being able to use them. How can I efficiently update a specific element of the state when a prop changes, without causing an infini ...

How can I show the last li item in a ul element that extends beyond its parent container?

Chat App Development In my current project, I am developing a chat application using React. The app consists of a list (ul element) that displays messages through individual items (li elements). However, I have encountered an issue where the ul element st ...

What is the procedure for updating a user's password using mongoose?

I have a new feature on my website that allows users to reset their password if they forget it. Here are the packages I am using: Express Js (framework) passport-local--mongoose, passport-local, passport, I'm implementing the passport method . ...

Having trouble with Angular2's Maximum Call Stack Exceeded error when trying to display images?

I am facing an issue in my Angular2 application where I am trying to display an image in Uint8Array format. The problem arises when the image size exceeds ~300Kb, resulting in a 'Maximum Call Stack Exceeded' error. Currently, I have been able to ...

Sending an array of dictionary objects to a JavaScript function

I have a situation where I need to pass a large amount of data stored in an NSArray containing NSDictionary objects to a JavaScript function using a webview and the method: - (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script My inquir ...

Show dynamic HTML Dropdowns with nested JSON data

I've been racking my brains trying to implement this specific functionality in the UI using a combination of HTML5, Bootstrap, CSS, and JavaScript. My goal is to create dropdown menus in the UI by parsing JSON input data. Please Note: The keys withi ...

Obtaining user data in Angular post login

My goal is to retrieve user data and display it anywhere on my website. For example, I want to fetch the user's name and show it on the homepage once they are logged in. Any suggestions? Thank you AuthService import { Injectable } from '@angula ...

Refreshing select2 dropdown options dynamically with AJAX updates

I have a select dropdown for locations that is initialized using select2 on page load. I am looking to dynamically update the data in the dropdown at regular intervals using ajax calls. However, when I attempt to update the data in select2, the dropdown ...

When using Turbolinks, signing out in a separate browser tab may become necessary for a

My Rails 4 application has two layouts; one for users who are logged out and another for those who are logged in. These layouts utilize different stylesheets. The issue arises when I have multiple browser tabs open and log out of one tab. The other tab st ...

The radio button's checked attribute fails to function

I am currently working on adding a hover effect to radio button labels, and while it is functioning correctly, I would like to achieve the following: When a radio button is selected, I want the corresponding label to have a background color. Despite tryi ...

Oops! Looks like we have encountered an issue with reading the property 'checked' of nothing

Whenever I click the checkbox, an image should be displayed. Unfortunately, I encountered an error: Uncaught TypeError: Cannot read property 'checked' of null at (index):185 at dispatch (VM576 jquery.min.js:3) at i (VM5 ...

I am attempting to use AJAX and PHP to upload multiple images, but I keep encountering an error

Within my form.php file <form method="POST" enctype="multipart/form-data"> <input type="file" name="file_upload[]" id="file_upload" style="display:none;" required multiple accept=" ...

Detect a modification event on a field lacking an ID using jQuery

I'm currently facing some challenges with jQuery and I really need to overcome them in order to complete the code I'm working on. The issue is that I can control the img tag, but unfortunately, I am unable to assign an ID to the input tag as des ...

Discovering unutilized node modules in your React project - A practical guide

Looking for a way to clean up unnecessary node modules and their dependencies from a project. I've done some research online and came across a few NPM packages that claim to achieve this, but none seem to meet my specific needs. Important: Node modu ...

How to partially update a function in Javascript without affecting specific lines of code

Straight to the point. I am working with a function inside a javascript class. For example: export default class gf{ iLoveThis(){ this.state.MakeMeWhole = true; callBoyfriend(); } } My goal is to override this method in another JS ...

Increase the object name in localStorage to save information entered in input fields

For testing purposes only - do not use for production. I am experimenting with storing data from 3 different input fields (text and numbers) in localStorage. My goal is to have the values increment every time the form is submitted. However, I am encounte ...