Limiting the Frequency of Event Triggers: How to Improve Efficiency

let time = null;
let bounds = null;
google.maps.event.addListener(map,'bounds_changed',function(){
    bounds = map.getBounds();
    time = (new Date()).getTime();
    setTimeout(function(){
        let now = ((new Date()).getTime() - 999);
        if(now > time){
            console.log('now: '+now+ ' then: '+time+ ' diff: '+(now-time));
            // here I want to fire an event exactly 1 time instead of a baizllion
            alert('I just want to see this once after the map was moved');
        }
    },1000);
});

Essentially, when the map changes, the bounds_changed event seems to trigger quite frequently. My assumption that declaring time outside would prevent it from being overwritten may be incorrect.

Answer №1

Have you experimented with using the dragend event if you are solely dragging the map?

In other cases, a widely-used approach to deal with this issue is by utilizing a shared Timer. It seems like you are on the right track based on your code snippet.

Each time the bounds_changed event gets triggered, the timer is reset and once it reaches the set time limit, your desired function will be executed. The key is to extract the timer logic and make it accessible to all instances of the bounds_changed events.

Here is the link to APIv3

Updates:

You may want to consider trying the following implementation:

function fireEvent()
{
    if (lastEvent.getTime() + 500 <= new Date().getTime())
    {
        //your event
    }
}

function DelayedCallback()
{
    lastEvent = new Date();
    setTimeout(fireEvent, 500);
}
event.addListener(map, "bounds_changed", DelayedCallback);

Extracted from this source

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

Ways to recover HTML elements that have been eliminated by jQuery's remove

$(document).ready(function() { $('#remove').click(function() { $('.test').remove(); }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="test-wra ...

Trigger an alert when a button is clicked and redirect the user to an newly opened tab

I recently created a button with a link that opens in a new tab. I also implemented some JavaScript to display an alert. Everything is working as expected, but after the user clicks "OK" on the alert, they remain on the same page. I would like to automati ...

Modify mesh in three.js scene

Is there a way to dynamically change a mesh in a group triggered by a button click? I am loading an external .obj file: loader.load( obj, function ( object ) { createScene( object, mod.tipo, pid, cor.replace("#","0x") ); }); and adding it to a gro ...

Discover the status of appcache on a webpage even without a manifest file by utilizing an iframe

Looking to cache two important pages of my web application using Application Cache. Successfully implemented with the iframe technique to specifically cache those two pages without caching the manifest-calling page. However, encountering an issue where I ...

To avoid any sudden movements on the page when adding elements to the DOM using jQuery, is there a way to prevent the page from

I have a challenge where I am moving a DIV from a hidden iFrame to the top of a page using jQuery. Here is my current code: $(document).ready(function($) { $('#precontainer').clone().insertBefore(parent.document.querySelectorAll(".maincontainer" ...

Why do React components require immutable props when values are passed by value regardless?

I am not deeply knowledgeable in JavaScript, so I have been experimenting with some code: var demo = 'test'; var obj = { x: 'abc' } function foo(str) { str += '_123'; ...

How can we pass the onClick prop from a child component to a parent component in React with Typescript?

Currently, I am utilizing React along with TypeScript. I am curious about the process of passing an event from the parent component to a child component using props. Here is an example for better understanding: parent.tsx const ParentComponent: React.F ...

Trouble with X-editable: Unable to view values when editing and setting values using J

When using X-editable to modify a form with data, I encounter an issue. Initially, the values are loaded from the database to the HTML, but when users try to edit by clicking on the "Edit" button, all values appear as "Empty" instead of their actual cont ...

Is there a way to set the background image to scroll vertically in a looping pattern?

Is it possible to achieve this using only HTML5 and CSS3, or is JavaScript/jQuery necessary? ...

A guide on organizing a JSON object in JavaScript/AngularJS through grouping

My JSON object contains zip code entries organized by the "Zipcode" key. My goal is to group these entries by zip code to display which zone IDs are associated with each zip code. For example, zip code 7 corresponds to zone IDs 12005, 12008, 12006, and 1 ...

Recharge the Div

Looking for a solution to refresh the content within a specific div, I have implemented the following code: <script> $(function() { $("#refresh").click(function() { $("#new").load("/new.php") }) }) </script> The issue I am facing is ...

Retrieve the width and height of the browser once the user has adjusted the window size

Can the browser width and height be accessed after a user resizes the window? For instance, if the window is initially 1920 by 1080 and the user changes it to 500 by 500, is there a method in JavaScript or jQuery to retrieve these new dimensions? ...

Leveraging greensock with browserify

Having trouble integrating TweenLite with browserify. I'm still learning about CommonJS and could use some help. Installed gasp v1.13.2 via Bower, including it like this: var TweenLite = require("../../bower_components/gsap/src/minified/TweenLite.mi ...

Is there a way to obtain the Base64 data following the conversion of a div to an image?

I am not very experienced with JavaScript, but I wanted to convert a div to an image. I came across this helpful jsfiddle that showed me how to do it. $(function() { $("#btnSave").click(function() { html2canvas($("#widget"), { on ...

What is the best way to position a static element next to a Vue draggable list?

I'm currently working on implementing a feature to display a list of draggable elements using vue-draggable. These elements are occasionally separated by a fixed element at specified position(s). My approach so far has involved creating a separate el ...

What methods are available for updating the href color of an element using the DOM?

I am looking to update the color of a tab (Mathematics-tab) based on the value of 'aria-selected' changing to true in Bootstrap. I have multiple tabs, including one for mathematics, and I want to visually differentiate between selected and unsele ...

Seeking help with executing JQuery Ajax functions within a foreach loop

Currently, I am engrossed in the study of programming and endeavoring to construct a website utilizing .Net Core. The predicament at hand pertains to my limited acquaintance with JavaScript while incorporating two JQuery/AJAX functions on my Index page - o ...

What are the steps to switch the dropdown values?

I am facing an issue with swapping values in two dropdowns. The scenario is that I have a dropdown with minimal values and another one with maximum values. If a value selected in the first dropdown is greater than the value in the second dropdown, they nee ...

Tips for maintaining the data in localStorage when the app is rendering

I've encountered an issue with my localStorage implementation in my app. I've set it up to add +1 every time a user visits, but the value resets to 0 whenever the page is refreshed. This is the code snippet in question: localStorage.setItem(& ...

Guide on displaying a list of images in a single line with rows and columns

I am in search of a solution to create the user interface depicted in the attached image using React. Additionally, this post includes a link to another post on the same site: How to add a single line image list that is horizontal scrollable (in react js). ...