JavaScript, determining variable scope, sequence of evaluating variables

While testing an AngularJS app with Protractor, I have come across a perplexing issue:

var counter = 0;
redButton.click();
allImages.each(function(element) {
    element.isDisplayed().then(function(isDispl){
        if(isDispl === true){
            expect(element.getInnerHtml()).toContain('red');
            counter++;
            console.log("I'm here!")
        }
    });
});
console.log(counter);

The displayed output shows:

0
I'm here!
I'm here!

But what I expected was:

I'm here!
I'm here!
2

Why is this happening? Why does the variable 'counter' not equal 2 when the condition isDispl === true twice?

Answer №1

JavaScript allows only one function to run at a time, with some exceptions that exist.

The main function completes its execution fully before any other action takes place. As the function contains the code console.log(counter);, it prints the current value of counter.

After the function finishes running, the event loop is able to detect any events that have been triggered.

When the elements are displayed, their promises are fulfilled which triggers them twice, resulting in a message being output and the value of counter changing.

Because this occurs after the initial output of the value of counter, the value never reaches '2' while observing.

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

Create interactive charts with Highcharts by incorporating AJAX requests

Below is the code snippet for an AJAX request to retrieve data and then call a function to pass the data to a graph. function getGraphs(){ $.ajax({ type : "POST", async: true, url : "<?php echo base_url(); ?>" + "Graphs/get_graphs", ...

Utilizing React hook form to submit arrays with the help of React server actions

When attempting to submit an array for a field named services using react-hook-form, it is returning as a separate value upon submission. The data structure returned looks like this: { customerId: '', title: '', message: '', s ...

Is there a way to transfer the functionality of openssl_seal from PHP to NodeJS 18?

I'm looking to convert the openssl_seal() function from PHP to NodeJs. The code below is from my PHP SDK and works flawlessly, which is what I want to migrate: $ivLength = openssl_cipher_iv_length('AES-256-CBC') ?: 16; $iv = openssl_random ...

Select rows in Datatables with a dropdown feature

1) I am currently working on a project where I have implemented a data table with selectable rows (click to highlight/select a row). 2) Each row in the table contains a bootstrap dropdown menu within the last column. The Issue: When I click on a row, it ...

What are the best ways to engage with a div element using keyboard shortcuts?

Is it possible to enable keyboard shortcuts for interacting with div elements? I am working on a project tailored for seniors who may have difficulty using a mouse. Is there a way to utilize keyboard shortcuts to click on divs and access their contents? H ...

Error in Angular 1.6 caused by binding issues

Just started using Angular and encountering this issue. Error: Uncaught TypeError: Cannot use 'in' operator to search for '$ctrl' in subpackage I have a parent component and a child component where I have defined a function in the par ...

What is the best way to increase the amount of data being sorted on AngularJS by entering information into

I have the following: Html: <div ng-controller="repeatPeople"> <br> <p> <input type="text" id="search" ng-model="searchPeople" placeholder="Search" > </p><br><br> <table border="0"> <thea ...

Combining two objects by id and grouping identical key-value pairs together

var routePlan = [ { "id" : 1, "farmerName" : "Farmer1", "farmerId" : 1 }, { "id" : 2, "farmerName" : "Farmer2", "farmerId" : 2 }, { "id" : 1, "farmerName" : "Farm ...

Bidirectional data binding in Vue.js enables seamless communication between parent and child components, allowing for dynamic

Trying to implement v-for and v-model for two-way data binding in input forms. Looking to generate child components dynamically, but the parent's data object is not updating as expected. Here's how my template is structured: <div class="cont ...

Unable to transfer information from the Parent component to the Child component

Can you help me solve this strange issue? I am experiencing a problem where I am passing data from a parent component to a child component using a service method that returns data as Observable<DemoModel>. The issue is that when the child component ...

Can you provide guidance on how to use Javascript to submit a form specifically when the input name is labeled as "submit"?

Query: How can I use Javascript to submit a form when one of the form inputs is named submit? Scenario: I need to send users to another page using a hidden HTML form. Unfortunately, I cannot modify the names of the inputs in this form because it needs to ...

Tips for successfully using a string with a slash ("/") as a parameter in a route within vue.js

Currently, I am utilizing Vue Router with a specific route setup { path: '/my-route/:param?', component: MyComponent } To link to this route, I have created the following link <router-link :to="'/my-route/'+myParam">Link text&l ...

Various tasks to be executed on a shared element

Struggling with implementing actions on a grid component without using a router in Next.js. Here is the current code snippet: const handleActions = (btnPress, row) => { if (btnPress === "Add") {/* implementation */} else if (btnPr ...

Clarifying the Usage of mockjaxClear in Asynchronous Tests with QUnit

Testing out my frontend code with qunit and mockjax. The way AJAX tests are structured in mockjax's test code is shown below (jsfiddle): var testURL = "/test/data", testData = { a: 1, b: "c" }; asyncTest("AJAX response test", 1, function() { ...

Adding jQuery SVG Sources to SVG Elements

Can the jQuery SVG source code be included in a standalone SVG document? Here is an example: <script type="application/javascript"> <![CDATA[ // jQuery SVG code ]]> </script> I want the SVG document to be self-contained, ...

What is the best Bootstrap component to implement?

Can anyone provide guidance on utilising Bootstrap to design the upcoming page? I am interested in understanding which components are suitable for this particular scenario. ...

Troubleshooting: AngularJS ngRoute Issue - Uncaught Error: [$injector:modulerr]

I'm currently trying to diagnose the reason behind this error message that keeps popping up: Uncaught Error: [$injector:modulerr] Here's the code snippet from my index.html file: <!DOCTYPE html> <html ng-app="MainApp"> &l ...

I am confused about what my teacher wants me to do. Have I interpreted the task correctly?

I completed the assignment, but I'm still unclear if I have fully grasped my teacher's instructions. Can you provide some insight on this for me? I attempted to solve it using two arrays, a for-loop, and connecting a button with a function, and ...

Issue with XMLHttpRequest.send() not working in Google Chrome when using POST requests

I'm currently developing an application where users can send files using a form through a POST request. As the file uploads, the application makes multiple GET requests to gather information about the upload progress. Interestingly, this functionalit ...

Confirm the login form using JavaScript and PHP

I am working on a functionality where I need to either redirect a user to a restricted area or display a message saying Email and or password do not exist if the login credentials are incorrect. However, I'm facing issues as nothing happens regardless ...