once completion of the function (including any setTimeouts), proceed to call the next function

Greetings! I am currently working on an ajax call that includes this function:

for(var i in data){
    setTimeout((function(i) {
         return function(){
            CreateMarker(data[i]);
         };
     })(i), i*500);
    }

This function adds markers to a Google map, utilizing google.maps.Animation.DROP. I would like to change the drop animation to

setAnimation(google.maps.Animation.BOUNCE)
once all the markers are on the map. I do know how to switch animations.

My predicament is as follows: While I can determine when the ajax call has concluded, the timeout causes difficulty in identifying when all markers have been "dropped" onto the map, leading to delay in changing the animation.

Does anyone have suggestions on how I can accurately detect when all markers have been placed on the map so that I can modify the animation? Thank you!

Answer №1

To resolve the issue, consider adding an additional setTimeout statement after your for loop:

for(var i = 0; i<data.length; i++){ // assuming data is a contiguous array
  setTimeout((function(i) {
    return function(){
      CreateMarker(data[i]);
    };
  })(i), i*500);
}
setTimeout(changeAnimation, (i-1)*500); 

The changeAnimation function will run immediately following the last CreateMarker execution.


If you notice recurring patterns, it might be beneficial to substitute setTimeout with setInterval:

var interval = setInterval(function(){
  var markerData = data.shift(); // modifies data, make a copy if needed elsewhere
  if (markerData) CreateMarker(markerData);
  else { clearInterval(interval); changeAnimation() }
}, 500);

In this basic implementation, changeAnimation triggers 500ms after the CreateMarker call but could easily be adjusted to trigger immediately after:

var interval = setInterval(function(){
  var markerData = data.shift();
  CreateMarker(markerData);
  if (!data.length){ clearInterval(interval); changeAnimation() }
}, 500);

Answer №2

To keep track of the markers that have been placed, you can use a variable to count them and then check if all markers have been placed after each one is added.

var finishedMarkers = 0;

for(var index in markerData){
    setTimeout((function(index) {
        return function() {
            addMarkerToMap(markerData[index]);
            if (++finishedMarkers == markerData.length) {
                // Your code execution goes here
            }
        };
    })(index), index*500);
}

If you want to see this code in action with random data, check out this example: http://jsfiddle.net/XJ9ZQ/

Answer №3

To effectively manage timers and track the firing sequence, it is important to keep a count of the timers being used.

The versatility of this solution lies in its compatibility with both arrays and objects as the data variable type is not explicitly defined. However, it's worth noting that iterating through arrays with for (var i in data) is generally discouraged, so the assumption was made that data represents an object.

var timerCounter = 0;
for(var i in data){
    ++timerCounter;
    setTimeout((function(i) {
         return function(){
            CreateMarker(data[i]);
            if (--timerCounter === 0) {
                // signals the completion of the last timer
            }
         };
     })(i), i*500);
}

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

Angular Selectable Drop-down Menu

I'm facing an issue with using angularjs for dropdown with multiple selection. When I try to include 2 dropdowns in the same form, only one of them gets initialized properly. Here is a sample code snippet http://jsfiddle.net/vUSPu/1221/. Can someone p ...

Removing a hyperlink and adding a class to a unordered list generated in JavaScript - here's how!

In my JavaScript code, I have the following implementation: init: function() { var html = []; $.each(levels, function(nr) { html.push('<li><a href="#">'); html.push(nr+1); ...

Collaborating information between 2 controllers using a shared Service in Angular.js

(function () { 'use strict'; angular.module('ShoppingListCheckOff', []) .controller('ToBuyController', ToBuyController) .controller('AlreadyBoughtController', AlreadyBoughtController) .service("ShoppingListCheckOffS ...

What is the reason for this function outputting 20 console.log statements instead of just once?

My application.js file is set up to display all the 'topics' on the page from an ajax call, and when one is clicked, all the information should appear on the screen. Everything works perfectly in development mode, but I encounter a 500 server err ...

Choose all the items that are visible in the list using Angular

If you have the following ng-repeat: <ul class="list-group"> <ng-user-item ng-repeat="user in users | filter:search" user="user" ng-if="assigned.indexOf(user.id) < 0" ng-click="selectFunction(user);"></ng-use ...

The function get_template_directory_uri() returned an unexpected string error

Exploring WP themes has been an interesting journey for me. Currently, I am working on creating a shortcode for some html/script and encountering an issue with enqueuing the js file. My initial query is about whether I am loading this from the correct loc ...

Showing the outcome of the AJAX call

I have searched extensively for information on how to use AJAX, but I have been unable to find a resource that clearly explains the concept and its workings. When I send an AJAX request to a PHP file using the code below, I can see the response in Mozilla ...

Navigating with AngularJS Front-End Routing using ui-router

My routing in AngularJS involves using ui-router for managing states: $urlRouterProvider.otherwise('/Home'); $stateProvider .state('home', { url: '/Home', templateUrl: '/Home/Home', cont ...

React throwing error: Context value is undefined

Why is the Context value showing as undefined? The issue lies in src/Context.js: import React, { Component } from 'react'; const Context = React.createContext(); export class Provider extends Component { state = { a: 1, b: 2 }; render( ...

Converting part of a string into a numerical value using the toInt function

Currently, I am working on an Arduino project where I need to convert an Ajax request that has the following format: String request = "GET /setAlarm&h=21&m=34&end" The goal is to extract the integers "21" and "34" from this request and stor ...

Obtain the row ID in React's MUI-Datatables

I have a scenario where I am working with a table that displays two buttons, one for deleting and the other for editing a row. For both of these buttons, I need to access the specific row Id. I attempted to utilize customBodyRender but ran into an issue ...

Using Underscore.js debouncer for onresize events - managing .on() and .off() alongside Window Widths [Enquire.js]

In the following code snippet, vw (viewport width) font sizing is simulated only when the window width exceeds 375px. When the window width drops below 375px, jQuery disables resize.mymethod. /* This plugin mimics vw (viewport width) */ function Suppo ...

While iterating through the material-ui rating component, the 'index' value remains constant at 0 within the 'onChange' function

For my e-commerce React.js web app, I want to show the rating value of each product. Using the JS map function, I was able to track which product was hovered by its index ('onChangeActive' is the handler for this). {products.map((product, index) ...

The lighting discrepancies on Three.js planes do not align with the material used

After creating a shape in Three.Js by combining a curved plane and two flat planes, I encountered an issue. While the vertical plane and curved plane blend seamlessly, there is a noticeable harsh line where the horizontal plane meets the curve. The lightin ...

Database entry issue: PHP form is not submitting via AJAX

I've been struggling to make this work for quite some time now, and I have gone through numerous responses to similar queries (How to add AJAX Submit to PHP validation and return message? , ajax submit form why it cannot echo $_POST) but unfortunately ...

Is a single f.select impacting another f.select in the same form? (undesired)

I am facing an issue where adding a new HTML element like: <%= f.date_select :date, { id: "date-select"} %> is impacting my existing collection select: <%= f.collection_select :id, Customer.where(business_id: current_c ...

Is React the best solution for managing a lengthy list that requires constant data updates?

In order to display a long list with over 2000 entries that changes dynamically, I am utilizing react redux. Each second, at least one new row is added to the list data. My current approach involves mapping through the list data in the render method like t ...

What is the best way to configure angular $filter to perform case-sensitive string comparisons when filtering data?

I've been working on creating a case-sensitive filter in an Angular controller to filter an array. Here is the data: var stoneArr = [ { "stone_name": "Diamond", "id": 16 }, { "stone_name": "Ruby", "id": 1 ...

Creating dynamic HTML table rows with data from a JSON object

Query: In search of a Jquery or JavaScript solution for generating dynamic table rows with colspan using the JSON structure provided below. I am encountering difficulties in creating the necessary rows and have attempted several approaches without success ...

What is the preferred method for updating a variable value - Ajax or PHP?

I'm in the process of creating a dropdown survey for new visitors using cookies to collect data, but I'm a bit confused on how to implement it. If a button is clicked, the onClick event will trigger var answer1 = answer1 + 1 , or something simil ...