"Resetting the counter and adjusting the position on the screen: a step

Currently, I am in the middle of a tutorial series and working on a project to develop a reaction tester. Despite conducting thorough research online, I am struggling with resolving two specific issues and could really use some assistance.

When the game starts and the shape is clicked, it should display the time until the click event occurs while generating a random shape with unique attributes like color, size, and position.

My main objective is to reset the counter every time the shape is clicked and ensure that the shape remains within the boundaries of the window at all times.

However, the current setup continues to increment the counter without resetting it after each click, resulting in scenarios where the generated shape extends beyond the visible window area, requiring users to scroll to locate it.

I have attempted different approaches such as changing

var timeUntilClick = +new Date() - currentTime;
to var timeUntilClick = "";, but unfortunately, no success has been achieved so far.

If you would like to take a closer look at my code, please visit this JSFiddle link.

Answer №1

Your currentTime variable is set when you click on "start". Each time a new shape is created, you subtract the initial value of currentTime from the current time, causing the counter to increase. To fix this issue, make sure to reset the currentTime variable each time a new shape is created. Check out this modified version in this JSFiddle link.

Answer №2

Remember to adjust your currentTime value with each click.

currentTime += timeUntilClick;

To determine the position of your shape, one simple approach is to divide the available height and width evenly.

var w = window.innerWidth/2;
var h = window.innerHeight/2;

Check out the updated Fiddle here

Answer №3

Give this a shot.... demonstration

document.getElementById("startGame").onclick = function() {

  var currentTime = +new Date();

  document.getElementById("shape").onclick = function() {

    function randomIntFromInterval(min, max) {
      return Math.floor(Math.random() * (3500 - 500 + 1) + 500);
    }

    function insideContainer(position, dimension, max) {
      if (position + dimension >= max) {
        return max - dimension;
      }
      return position;
    }

    function generateRandomColor() {
      var letters = '0123456789ABCDEF';
      var color = '#';
      for (var i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
      }
      return color;
    }

    var randomColor = generateRandomColor();
    var randomShape = Math.round(Math.random());

    if (randomShape < 0.5) {
      randomShape = "50%";
    } else {
      randomShape = "10%";
    }

    var w = window.innerWidth;
    var h = window.innerHeight;

    var randomLeft = Math.floor(Math.random() * w);
    var randomTop = Math.floor(Math.random() * h);
    var randomWidth = Math.floor(Math.random() * (w / 2));
    var randomHeight = Math.floor(Math.random() * (h / 2));

    var elem = document.getElementById("shape").style;
    elem.backgroundColor = randomColor;
    elem.left = insideContainer(randomLeft, randomWidth, w) + "px";
    elem.top = insideContainer(randomTop, randomHeight, h) + "px";
    elem.borderRadius = randomShape;
    elem.width = randomWidth + "px";
    elem.height = randomHeight + "px";

    document.getElementById("shape").setAttribute("class", "hide");

    var timeUntilClick = +new Date() - currentTime;

    if (timeUntilClick > 999) {
      var timeUntilClick = timeUntilClick / 1000 + " seconds";
    } else {
      var timeUntilClick = timeUntilClick + " milliseconds";
    }

    document.getElementById("printTime").innerHTML = timeUntilClick;

    var randomDelay = randomIntFromInterval();

    setTimeout(delay, randomIntFromInterval());

    function delay() {
      document.getElementById("shape").removeAttribute("class", "hide");
      currentTime = +new Date();
    }

  }

}

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

Using javascript, how can you fill in the missing dates within an array of objects?

I need to populate this object with dates starting from today up to the next 7 days. Here is my current object: let obj = { "sessions": [{ "id": 0, "available_capacity": 3, "date": "15-05- ...

When utilizing Multer for file uploads, it logged an array that was mysteriously empty

I'm struggling to understand why I can't utilize express and multer in my current code. Whenever I try to upload a file, the log only shows an empty array. I've spent hours tweaking it, but I just can't seem to get it right! I've ...

Introducing the feature of adding an Opacity Slider specifically designed for the chosen object

I am trying to implement an opacity slider to adjust the visibility of selected objects based on the slider's position (100 indicates complete visibility). I am using fabric.js/master/dist/fabric.js and jQuery 3.3.1. Could you please help me identify ...

Resizing a d3 graph for various screen resolutions

Looking to create a dynamic dashboard in Angular, I found a code snippet for a gauge chart at this link. Here is an example of how my HTML file appears: <div fxLayout="row" fxLayoutAlign="space-around center" > <div fxFlex='33%'> ...

how to choose the :after pseudo-element with jQuery

Below are the codes I have tried. When this popup appears, I want to be able to close the entire popbox using the close button. CSS code .bigdiv{ display:none; background-color:#efefef; box-shadow: 10px 10px 10px 100000px rgba(0, 0, 0, 0.4); ...

JavaScript Selenium code encountering an "Element not interactable" error with input textbox element

Currently, I am attempting to utilize Selenium in order to automate inputting a location into the search bar on weather.com. Initially, I wrote the code in Python and it seems to be functioning properly: // this works driver = webdriver.Chrome(ChromeDriver ...

There are no markers or popups currently displayed on the map

Utilizing the ngx-leaflet plugin for leaflet, I have established the base layers and integrated a listener for the leafletMapReady event. Within my handler, I attempted to add both a marker and a customized popup. The handler code is displayed below: init ...

Proper method for incorporating client-side libraries (such as adminLTE) into Vue.js 2.0

Looking to merge adminLTE with vue. I've set up a fresh app using vue create admin-cli Next, I ran npm install admin-lte --save following the instructions in this link: Now npm is storing everything under node_modules/admin-lte I'm not quite ...

Develop an ASCX component to handle various tasks

I am currently in the process of developing a unique custom control that will feature two radio buttons. This project is being carried out using MVC4 and ASP.NET technology. At the moment, I have successfully created two sets of two radio buttons on separa ...

Tips for creating a blur effect on all options except for the selected 2 out of 4 using jQuery

My goal is to choose 3 options from a list and once 3 options are selected, all other options will be blurred to prevent further selection. Please review the code snippet I have provided below. Link to File <!DOCTYPE html> <html> <head> ...

Permit the use of HTML tags within an Angular controller or view

My controller : LandingApp.controller('LandingCtrl2', function($scope){ $scope.articles = [ { 'imageSrc' : IMG_DIR + 'spec9.jpg', 'title' : 'Stencils', ...

How can I utilize JavaScript to call a Delphi function in TWebBrowser on Delphi XE6 for all platforms, such as iOS and Android?

My goal is to develop an application using Delphi XE6 for Android and iOS that utilizes a TWebBrowser to display Google Maps. I need the ability to communicate between Delphi and JavaScript, allowing me to interact with markers on the map based on user inp ...

Transform the snake code by incorporating a visual image as the face of the serpent

Can someone help me change the snake's face to an image instead of a color fill in this code? And how can I add arrows for mobile compatibility? (function() { // Insert JS code here })(); // Insert CSS code here This code snippet includes functi ...

There is a necessary pause needed between carrying out two statements

I am currently working with extjs 4.2 and I have encountered a situation where I am loading the store object in the following manner: var userDetailStore = Ext.create('Ext.data.Store', { model: 'Person.DetailsModel', autoLoad: ...

Ways to adjust the text size in jqGrid?

The current theme is ui-lightness. How can I adjust the font size within the grid? Your suggestions are appreciated. Many thanks. ...

Using TypeORM in Javascript to create routes efficiently

After examining the TypeORM websites examples, I noticed that some of them demonstrate routing usage using TypeScript. Given that TypeORM has the capability to use JavaScript instead of TypeScript, I am seeking guidance on how to implement Express routing ...

What is the best way to transmit the server response information from a fetch API to the client?

After receiving a response with the expected results from an API call using fetch API and a json object, I am looking for ways to send these results to the client in order to display them on the interface. The server-side operation was conducted through th ...

Error in overwritePermissions caused by a bug

message.guild.channels.create(`ticket-${message.author.username}`).then (channel => channel.overwritePermissions(Support, { SEND_MESSAGES: true, READ_MESSAGES: true ...

Since switching to PHP 5.5 from version 3.x, I have noticed that it is attempting to interpret my JavaScript comment within a script tag in a PHP include file

After a long break from working with PHP, I recently encountered an issue with an older website I built using PHP and the include function. The site was functioning perfectly until the web host updated PHP to version 5.5, causing a strange bug where it see ...

Setting the variable to global does not apply styling to the element

Looking for help with styling an element created using document.createElement("img")? let fireball; //global variable fireball = document.createElement("img") //variable on local fireballArray.push(someFunction(fireball, { src: "img.png&qu ...