简体   繁体   中英

Javascript fire the last event

I'm coding a web application and I don't know how to keep on what I'm trying to do with Javascript.

I have a function that is fired when I do zoom on a map or when I move the map. I try to avoid this function do its stuff until it's been a while (2 seconds, for example). Ok, I can use a setInterval method to achieve it.

But what I want and I don't know how to do is... if I do zoom 3 times, very close in time between them, I just want to process the last zoom , not the two previuos ones. I mean, the 2 first function callings have to be cancelled, or something like that.

How could I do that?


Example (pseudo-code) of what I have:

function doStuff() {
    setInterval(function({
       // do some stuff here...
    }, 2000);
}

myMap.on('dragend', doStuff);  // If I move inside the map
myMap.on('zoomend', doStuff);  // If I do zoom on the map

What I´d try is to set capture the intervalID in a global varial everytime you start your interval; then when you fire the event you check if the variable is set, if it is, you use the clearInterval function to cancel the previous interval before starting the next one.

Something like this:

var intervalID = 0;

function doStuff(){
  if(intervalID != 0){
    window.clearInterval(intervalID);
  }
  intervalID = setInterval(function({
       // do some stuff here...
       intervalID = 0; // try reseting the intevalID on completion, not sure if here
  }, 2000);

//  Your stuff

https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearInterval

You could use a object.addEventListener('load', function()) -function.

The function inside it will fire after the object has loaded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM