Meteor.setTimeout function doesn't work

北慕城南 提交于 2019-12-11 08:36:08

问题


I've looked around the internet for quite a while trying to figuring out what's wrong with my code and couldn't find a working answer.

Template.map.onCreated(function() {
    Meteor.setTimeout(function() {
      GoogleMaps.ready('exampleMap', function(map) {
        var marker = new google.maps.Marker({
          position: map.options.center,
          map: map.instance
        });
      });
    }, 2000);
  });

I'm simply trying to set a 2 seconds delay for the GoogleMap function to trigger but it doesn't work. I've tried a lot of various things like declaring a var to my function and then trigger the setTimeout function anonymously, etc... But no luck... I don't get errors from console so I feel my code is well written and Meteor docs doesn't provide much information on the setTimeout function.

This doesn't work as well:

Template.map.onRendered(function() {
  Tracker.afterFlush(function(){
    GoogleMaps.ready('exampleMap', function(map) {
      var marker = new google.maps.Marker({
        position: map.options.center,
        map: map.instance
      });
    });
  });
});

回答1:


Take your code inside setTimeout to a external function like this:

function prepareMap() {
      GoogleMaps.ready('exampleMap', function(map) {
        var marker = new google.maps.Marker({
          position: map.options.center,
          map: map.instance
        });
      });
    }
 }

And call the function inside the setTimeout without parenthesis, like this:

Template.map.onCreated(function() {
   setTimeout(prepareMap, 2000);
});

If you call the function using parenthesis the function will be executed immediately without the delay specified in the timeOut.



来源:https://stackoverflow.com/questions/31947774/meteor-settimeout-function-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!