开发者

Reduce number of times an event gets fired? [bad/incorrect title - change if you have a better one]

var time = null;
var bounds = null;
google.maps.event.addListener(map,'bounds_changed',function(){
    bounds = map.getBounds();
    time = (new Date()).getTime();
    setTimeout(function(){
        var 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);
});

Basically when the map changes the bounds_changed seems to trigger quite a lot. I thought that if I declare time outside it would be overwritten. Maybe wrong?


If you are only dragging the map, have you tried the dragend event?

Otherwise, I think the use of a shared Timer is a common way to overcome this. You probably have the right idea reading your code snippet.

Every trigger of the bounds_changed event resets the timer, when time's up, the timer triggers your desired function. You just need to move the timer out and share it amongs all the bounds_changed events.

the APIv3 link

Updates

You can try:

    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);

taken from here

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜