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

"Have you ever wondered how the router object in express.js is seamlessly integrated with app.use(), considering that it only accepts

I am curious about the process of how the router object in express.js is passed to app.use(), which typically only accepts callbacks. Since router is an object of express, I am trying to understand why app.use() does not throw an error even though it req ...

What is the best way to exchange configuration data among Javascript, Python, and CSS within my Django application?

How can I efficiently configure Javascript, Django templates, Python code, and CSS that all rely on the same data? For example, let's say I have a browser-side entry widget written in Javascript that interacts with an embedded Java app. Once the user ...

Asynchronous Await Eagerly Anticipates Promise Status: <awaiting

Struggling to implement async/await in an express route and encountering issues. Despite referencing various SO posts, it seems like my implementation is correct. Helpers: module.exports = { facebook: function(userId, token) { return new Promise(re ...

The React component is experiencing a delay in its updates

I've been experiencing delayed updates when using React.useEffect(). Can anyone shed some light on why this might be happening? function Process(props) { const [results, setResults] = React.useState({ number: "", f: {} }); let ...

Backand - How can I display the contents of variables using console.log() within Security Actions?

Is there a way to utilize console.log() in Backand, specifically within the server side functions like those found under Security & Auth > Security Actions? I have checked the Read.me which suggests using 'console.log(object) and console.error(object) ...

Passing an array of selected values from Vue.js to a text area and adding them to the existing content

I'm facing a situation and I could really use some assistance. The image shows that there is a multiple select box on the left with numbers, and a text box on the right. My goal is to allow users to click on the house numbers in the select box and hav ...

Troubleshooting image loading issues when updating the base URL in an Angular JS project

I am trying to update the base URL for my application. Currently, when I load the application, the URL shows up as http://localhost:4200/#/, but I want it to be http://localhost:4200/carrom/ instead. To accomplish this, I modified the base URL and now th ...

Use Javascript to deactivate the mouse cursor and rely solely on the keyboard cursor for navigation

I am facing an issue with a div that contains a textarea. The cursor is automatically positioned at the beginning of the text within the textarea. I would like to disable the mouse cursor when hovering over the textarea but still be able to navigate within ...

Vue and Axios encountered a CORS error stating that the 'Access-Control-Allow-Origin' header is missing on the requested resource

I've encountered the error above while using Axios for a GET request to an external API. Despite consulting the Mozilla documentation, conducting thorough research, and experimenting with different approaches, I haven't made any progress. I&apos ...

Having trouble importing the d3-geo package into a Node.js TypeScript project

Seeking a way to test the inclusion of specific latitude and longitude coordinates within different GeoJSON Features using code. When attempting this with: import d3 from 'd3-geo'; // or: import * as d3 from 'd3-geo' // no difference ...

Schema-specific conditions for JSON data

I have been experimenting with the if-then-else statement in JSON, but I am encountering some issues with it. { "type": "object", "minProperties": 2, "maxProperties": 2, "properties": { "human": { "enum": [ "Kids", "Ad ...

Executing a complex xpath using Java Script Executor in Selenium WebDriver

When working with a large grid and trying to find an element using XPath, I encountered some difficulties. The XPath used was: By.xpath("//div[contains(text(),'" +EnteredCompetitionName+ "')]/preceding- sibling::div[contains(concat(' &apo ...

Uniquely tag an uploaded file

My code for uploading files is as follows: var xhr = new XMLHttpRequest(); xhr.upload.addEventListener("progress", uploadProgress, false); xhr.open("POST", requestUrl, true); xhr.send(f); I want to draw your attention to the fact that I have attached a l ...

Increasing the top padding of a resized iframe thanks to iframe-resizer

Currently, I am utilizing the remarkable iframe-resizer library to resize an iFrame while keeping it in focus. The challenge I am facing is my inability to figure out how to include additional padding at the top of the iFrame once it's resized. The ...

JavaScript function failing to properly handle PHP array input

I am facing an issue with a PHP array that I am trying to pass to a JavaScript function using "json_encode($array)". Every time I click the button to trigger the function, the page simply refreshes without any action being taken. I have attempted to troub ...

The issue with ng-if not functioning within ng-repeat is that the ng-if directive

My issue is with using ng-if inside an ng-repeat in AngularJS. Despite updating to the latest version on 09/27/2014, I am still unable to make it work properly. The code functions perfectly outside of ng-repeat, and also works fine inside ng-repeat when us ...

How is it possible that my code is continuing to run when it is supposed to be

My API has a limitation of 50 requests per minute for any endpoint. In the code snippet below, I filter objects called orders based on their URLs and store the ones that return data in successfulResponses within my app.component.ts. Promise.all( orders.ma ...

Issue with Retrieving a particular table from SQL Server using mssql in javascript ('dbo.index')

I am currently experiencing an issue with trying to access a table named dbo.Index from SQL Server in my node js express application. Unfortunately, whenever I attempt to do so, the operation fails and returns no data. Below is the code snippet in questio ...

The functionality of Angular ng-show may be affected when utilized within a parent element containing ng

I am encountering an issue in my view where a parent div has ng-if applied to it, and some child elements have ng-show. The problem arises when the ng-show does not seem to work properly when nested under an element with ng-if. I'm unsure if this is a ...

Utilize the Google Maps API to align an SVG symbol with the direction of an aircraft's

I have been struggling to update the rotation of the Google Maps API SVG aircraft symbol to display the correct heading as it moves. Although it initially loads with the correct heading, I can't seem to figure out how to dynamically update it. I' ...