timings and pauses utilizing JavaScript

Currently, I am facing a challenge while working on a Simon Says game. My struggle lies in the part where I need to illuminate the buttons that the user has to click. I am using a "for" loop to iterate through each element in the array where I have stored the sequence. The aim is to traverse through the array for each round and illuminate the button accordingly. However, I am encountering an issue where the "for" loop is simultaneously changing the background of every div that has passed in the array, despite using a setTimeout function to pause at each button.

If you'd like to take a look at the codepen I am working on, here is the link:

https://codepen.io/argestis/pen/gLraBq?editors=0011

function litSequence() {
  for (var i = 0; i < game.count.length; i++) {
    if (game.count[i] === 1) {
      game.blue.css("background-color", "cyan");
      setTimeout(function() {
        game.blue.css("background-color", "blue");
      }, 1500);

    } else if (game.count[i] === 2) {
      game.red.css("background-color", "pink");
      setTimeout(function() {
        game.red.css("background-color", "red");
      }, 1500);

    } else if (game.count[i] === 3) {
      game.green.css("background-color", " #4dff4d");
      setTimeout(function() {
        game.green.css("background-color", "green");
      }, 1500);

    } else if (game.count[i] === 4) {
      game.yellow.css("background-color", "orange");
      setTimeout(function() {
        game.yellow.css("background-color", "yellow");
      }, 1500);
    }
  }
};

Answer №1

When you use setTimeout, it doesn't halt your logic. Instead, it sets up a separate line of logic to execute after a specified time delay. Your main logic will continue running in the background, and only once the timeout finishes will the code inside it be executed. Because JavaScript is known for its speed, it's common for multiple setTimeouts within loops to fire almost simultaneously.

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

Unable to pass on error from Express server to React client app

Background Overview In my project, I've implemented a React component named 'Register.jsx' where users can input their desired username and password. Upon clicking the submit button, this information is transmitted to an Express backend whi ...

Utilizing CSS for styling a class with a dynamic name

On the server side, I am dynamically generating class names like this: <p class="level_1">List item 1</p> <p class="level_2">List item 2</p> <p class="level_3">List item 3</p> <p class="level_1">List item 1</p& ...

NodeJS - The function app.listen is not defined in this context

I've come across a similar question before, but the answers provided didn't help me resolve my issue. The error message I'm getting is "TypeError: app.listen is not a function"; Here's my full code below. Thank you in advance for your ...

What is the best way to automatically place the cursor in a text box when a webpage is loaded using JavaScript?

Just starting out in web development and looking to enhance my skills. I am trying to find a way to automatically place the cursor in a specific text box on a website when the page loads. Currently, I am experimenting with the Greasemonkey add-on for this ...

Creating a function in Angular to locate each object based on its ID

Hello there, I am currently working on creating a method called findChildByIdInData(data:any, childId:string). This method will take in a JSON main node with children that have unique IDs, and the goal is to find a specific object based on the ID provided ...

Is there a way to eliminate the additional and varying pseudo-padding on text inputs in both Webkit and Gecko browsers?

The issue I'm facing is specific to input[type="text"] elements in Webkit. No matter what adjustments I make, it seems like there is an additional padding: 1px 0 0 1px (top and left only) applied to the element. A similar anomaly occurs in Gecko as w ...

The absence of FormData.entries in submit is a limitation of the Vue framework

I recently created a Vue-App that consists of a simple form with just one <input name"surname"> and a <button type="submit">. The use case is to input "myname" and submit the form. However, when I initialize new FormData( ...

Tips for refreshing innerHTML without altering the entire content

I've written a JavaScript code that uses AJAX to periodically send an XMLHttpRequest to fetch data from a PHP file. The data retrieved is then added to the innerHTML of a <p> tag. However, every time new content is added, the entire paragraph se ...

PHP: Retrieving a selection value without the use of a submit button

I am trying to access and utilize the select value in my current PHP file, but without the use of a submit button. How can I accomplish this? Here is the code snippet I am working with: <?php $args = array( 'orderby' =&g ...

Using the md-date-picker along with the md-menu component

Whenever I try to click on the md-date-picker inside md-menu, it unexpectedly closes. You can view the issue on this CodePen link. This seems to be a bug related to ng-material as discussed in this GitHub issue. Any suggestions for a workaround? Here is t ...

Encountering a connection issue: SMTP connect() failure when using PHPmailer with reCaptcha on a CentOS server

My company is looking to set up a website on a CentOS server that includes a contact form with captcha. I came across PHPMailer and got the code working on my local machine, but when trying to send emails on CentOS, I encountered an error saying "SMTP conn ...

Using ASP.NET MVC with JQuery to find the closest HiddenFor value

My current table structure is as follows: <table class="table table-bordered"> @for (var i = 0; i < Model.Count; i++) { <tr> <td width="25px"> @if (!Model[i].Letter.Equ ...

How can you modify the starting point of data in jQuery flot?

Currently using Flot to create a graph displaying clicks per minute within the first 60 minutes of short URLs generated at . The graph currently displays data from minute 0 to minute 59. My query is about adjusting the data to start at 1 and end at 59, wh ...

Retrieving selected values from an ngx dropdown list

I am having trouble implementing ngx dropdown list in this way: <ngx-dropdown-list [items]="categoryItems" id="categoriesofdata" [multiSelection]="true" [placeHolder]="'Select categories'"></ngx-dropdown-list> ...

The error message "POST .../wp-admin/admin-ajax.php net::ERR_CONNECTION_CLOSED" appears when a WordPress AJAX request receives data that exceeds 1MB in size

When I attempt to submit a jquery ajax form from the frontend and upload a blob (a variable of string) as a .txt file to WordPress using wp_handle_upload(), everything works smoothly until the file size reaches around 1mb. At that point, an error is displa ...

Is it possible to time a page without relying on the Form tag?

As I search for solutions, I have come across some examples that require a Form tag, but unfortunately, it doesn't seem to integrate well with my current application. My goal is to implement a timer on a webpage that starts counting when one button i ...

Exploring the dichotomy between controlled and uncontrolled elements within React. The _class attribute causing unexpected changes in an un

I created a custom Checkbox component that is essentially a styled checkbox with a 'fake element' acting as the original one. Custom Checkbox Component import React, {Component} from 'react'; import FormGroup from 'react-bootstra ...

Tips for creating a responsive input field within a navbar

Can anyone assist me with setting the input field width in my navbar to adjust to the remaining width of the navbar and be responsive to different device sizes? I need the input field to dynamically change its width based on the screen size. Any help would ...

Harnessing PHP-grown JSON to retrieve information using JQuery

After successfully using Alert on the response parameter in jQuery, I can see the values I need. However, the issue arises when trying to extract them using key/value pairs. I'm not sure if this is a compatibility problem with the JSON format from PHP ...

What is the reasoning behind the "open in a new tab" function triggering a GET request?

Check out this HTML tag: <a href="#" id="navBar_navBarInput_3_subNavDropdownInput_0_subNavLinkInput_0" onclick="redirectPost(4,'EntryData.aspx');">My Cool Link</a> The Javascript function "redirectPost" function redirectPost(id, ur ...