Angular/JS - setTimeout function is triggered only upon the occurrence of a mouse click

I'm currently working on a website that calculates the shortest path between two points in a grid utilizing AngularJS.

Although I have already implemented the algorithm and can display the colored path, I am facing an issue where the color changes tile by tile with a delay of 1 second using setTimeout. However, for some reason, the tiles are changing their color only after a mouse click event occurs, which is not the expected behavior.

For instance, when the first tile changes its color, it takes about 3 seconds and a mouse click for the next 4 tiles to change their color, and this pattern continues as time passes.

I suspected that the problem might be related to event listeners, but even after removing them post usage, the issue persists.


EDIT:

function colorThePath(tile) {
  tile.color = "purple";
}

for (var i = 0; i < shortestPath.length - 1; i++) {
  if (shortestPath[i] == 'East') {
    $interval(function() {
      colorThePath(self.board[self.startTile.x][self.startTile.y + 1])
    }, 2000, 1);
    self.startTile = self.board[self.startTile.x][self.startTile.y + 1];
  } else if (shortestPath[i] == 'South') {
    self.board[self.startTile.x + 1][self.startTile.y].color = "purple";
    self.startTile = self.board[self.startTile.x + 1][self.startTile.y];
  } else if (shortestPath[i] == 'West') {
    self.board[self.startTile.x][self.startTile.y - 1].color = "purple";
    self.startTile = self.board[self.startTile.x][self.startTile.y - 1];
  } else if (shortestPath[i] == 'North') {
    self.board[self.startTile.x - 1][self.startTile.y].color = "purple";
    self.startTile = self.board[self.startTile.x - 1][self.startTile.y];
  }
}

The process of coloring the path occurs within the "go" function located at the end of the JavaScript file.

HTML code:

<!doctype html>

<html ng-app="myApp">
<head>
<meta charset="utf-8>

<title>Main</title>
<!-- angular -->
<script src="../scripts/angular.js"></script>
<script type="text/javascript" src="../scripts/angular-ui-router.js"></script>
<!-- Angular Material style sheet -->
<link rel="stylesheet"
href="https://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.min.css">
<!-- Angular Material Library -->
<script
src="https://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.min.js"></script>

<script type="text/javascript" src="../scripts/MainRoute.js"></script>
<script type="text/javascript" src="../scripts/mainController.js"></script>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="../css/a.css"></link>
</head>

<body ng-controller="mainController as m>
<div id="navBar">
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="#">WebSiteName</a>
</div>
<ul class="nav navbar-nav">
<li class="active"><a href="#">Home</a></li>
<li><a ng-click="m.start()">Start</a></li>
<li><a ng-click="m.end()">End</a></li>
<li><a ng-click="m.go()">Go!</a></li>
</ul>
</div>
</nav>
</div>

<div>
<table id="table">
<tr ng-repeat="r in m.board">
<td ng-repeat="x in r track by x.id" style="background-color: {{x.color}}" ng-click="m.changeColor(x.id)" id="{{x.id}}">{{x.id}}</td>
</tr>
</table>
</div>
</body>
</html>

JS/Angular Code:

!-- begin snippet: js hide: false console: true babel: false --

(function() {

    var module = angular.module("myApp");
    module.controller("mainController", mainControllerCTOR)

    function mainControllerCTOR() {
        this.board;
        this.startTile;
        this.endTile;

        var self = this;

        function Tile(x, y) {
            this.id = x + "," + y;
            this.x = x;
            this.y = y;
            this.pressed = false;
            this.color = "yellow";
            this.secret = 'Empty';
        }

        window.onload = function() {
            self.board = [];
            for (var i = 0; i < 12; i++) {
                self.board[i] = [];
                for (var j = 0; j < 12; j++) {
                    self.board[i][j] = new Tile(i, j);
                }
            }
        }

        // Rest of the JS code remains same

    }
})();

Answer №1

It's important to note that the Angular digest loop may not catch events triggered by setTimeout. If you encounter this issue, consider using $timeout instead. Visit this link for more information.

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

Is it possible to add to JSON formatting?

Here is the JSON object I have: new Ajax.Request(url, { method: 'post', contentType: "application/x-www-form-urlencoded", parameters: { "javax.faces.ViewState": encodedViewState, "client-id": options._clientId, ...

Solve the error "Property 'container' of null is not accessible" in musickit.js while running an Angular application on a server

I am currently developing an application that combines Angular and MusicKit to offer users the ability to listen to music simultaneously. However, I encountered a challenging error when trying to run the application using ng serve --host x.x.x.x instead of ...

Guide on enabling a new input field in React when a dropdown option is selected by a user

I'm attempting to show an additional input field when the user selects "Other" from the dropdown menu. I have implemented a state for the input field that toggles between true and false based on the selected value from the dropdown. However, I am enco ...

"NaN is being caused by the presence of quotation marks within the split property

Apologies if this question has already been addressed, but I'm struggling to find the answer. I've recently delved into coding as a new hobby and found it quite enjoyable. After using a website that claimed I had learned all there is to know abou ...

An AJAX function nested within another AJAX function

Is there a way for me to return the second ajax call as the result of the ajax function? I could use some assistance with this. function ajax(url: string, method:string, data:any = null) { var _this = this; return this.csrfWithoutDone().done(funct ...

AngularJS select ng-model not correctly updating values

My form features a simple select element containing all the states along with their abbreviations. When I use the keyboard to navigate, I encounter an issue where the ng-model value does not change properly on the second keypress under certain circumstance ...

Using a three.js texture with a JSON object

Currently, I am working on a customization project where I am using three.js to export an HTML5 canvas as a 3D preview. My goal is to have the texture placed only on the front side, but it seems to appear on all sides instead. This is the code I am using: ...

Issue encountered during Azure DevOps pipeline release: D:a 1a***.zip angular - No package matching the specified pattern was discovered

My Angular project stored in an Azure DevOps repository successfully builds using the DevOps build pipeline. However, when it comes to the release, it consistently fails with the following error message: Error: No package found with specified pattern: D:& ...

Implementing a nested ng-repeat for organizing limited data

I'm working with a nested ng-repeat setup like this: <div ng-repeat="item_l in list1"> <div ng-repeat="item_f in list2"> {{item_f}} {{item_l}} </div> </div> Currently, this code is producing around 20 results. ...

Finding out if an array is empty or not in Reactjs: A Quick Guide

I am currently working with Reactjs and Nextjs. I am using axios to fetch data, and I need a way to determine if the array (students.data) is empty before running a map or loop. How can I achieve this? Here is the code snippet I am working with: const [stu ...

Generating forms dynamically using JSON data

Currently, I'm using three nested ng-repeat directives to display multiple questions and their corresponding answers. Everything is displaying correctly so far, but now I need to create a form to save the answers. What would be the best approach to ac ...

Is it possible to change the button class within a div while ensuring only the last one retains the change?

Here is a code snippet I'm using to switch between classes for buttons: $('button').on('click', function(){ var btn=$(this); if(btn.attr('class')=='tct-button'){ btn.removeClass('tct-button ...

How can I use the same popup button to open a different link in a new tab?

I have a situation where I am using a button to trigger an ajax html popup. What I want is for the same button, when clicked, to open another page in a new tab. Any assistance would be greatly appreciated. Below is the HTML code I am currently using: < ...

"Converting jQuery Form into a Wizard feature with the ability to hide specific steps

I'm working on a form where I need to hide a fieldset when a specific event is triggered. Inside the first fieldset, there is a select tag and when a certain option is selected, the second fieldset should be hidden. <form id="form1"> <fi ...

Text flashing in and out of view while utilizing angular translation

I am dealing with a main file and some partials being included in it. I want to access the translated content in both the main file and the partial files as shown below: <p>{{ 'HEADLINE' | translate }}</p> The content translated fro ...

encountered net::ERR_EMPTY_RESPONSE while attempting to locate a CSS file within an AngularJS directive

Every time my webpage attempts to access the css file from a directive, I encounter a net::ERR_EMPTY_RESPONSE. I have implemented door3's on-demand css feature, which allows for lazy loading of css files only when necessary. This feature works flawle ...

When information is provided, record the values in a separate input field

I'm struggling to come up with an appropriate title... Here's the issue: if a user inputs anything into the "Accompanying Person" field, the "Accompanying Person Price" field will automatically be set to 260€. I have no clue on how to achieve ...

How to access additional legend labels in c3.js or billboard.js using JSON data?

I'm working with the following code snippet: ... normen is my json object .... $.each(normen, function(item) { chartX.push(this.feed_day) chartY.push(this.weight) }); createChart(char ...

What are some strategies for breaking down large components in React?

Picture yourself working on a complex component, with multiple methods to handle a specific task. As you continue developing this component, you may consider refactoring it by breaking it down into smaller parts, resembling molecules composed of atoms (it ...

Steps for implementing a single proxy in JavaScript AJAX with SOAP, mirroring the functionality of the WCF Test Client

I am working with a WCF web Service and a javascript client that connects to this service via AJAX using SOAP 1.2. My goal is to pass a parameter to instruct the AJAX SOAP call to use only one proxy, similar to how it is done in the WCF Test Client by unch ...