Meteor.setTimeout is not causing delay

864 views Asked by At

I am creating my first Meteor app with the Spheron smart package. I can control he sphero ok and change it's colors but I'm trying to create a delay in between the color change.
Here is my code:

function makePrettyLights(sphero,color){   
    var colors = [];
    colors['red'] = '0xB36305';
    colors['green'] = '0xE32017';
    colors['blue'] = '0xFFD300';

    console.log(color);

    var spheroPort = '/dev/tty.Sphero-OBB-RN-SPP';
    var timer = 2000;
    Meteor.setTimeout(function(){

        sphero.on('open', function() {
            sphero.setRGB(colors[lineName], false);
        });
        sphero.open(spheroPort);

    },2000);
}

This function is being called from in a loop. I havent included the loop at it involves me parsing some xml and other bits but it works.

if (Meteor.isServer) {
   /**** Loop Code Here ****/
   makePrettyLights(sphero,color)
   /****End Loop Code ****/
}

I have also tried setting the timeout wrapper around the function where it is called instead of inside it.
But basically they all run at the end of my code at the same time.
I20140806-09:49:35.946(1)? set color
I20140806-09:49:35.946(1)? set color
I20140806-09:49:35.946(1)? set color

2

There are 2 answers

0
Tarang On

Your sphero variable is scoped outside the timeout. So every time a connection is opened the previously added callbacks will fire at the same time since you're just adding on to globally scoped sphero variable.

Try defining sphero (not currently shown with your code above) inside the Meteor.setTimeout callback instead of outside of it.

0
Hubert OG On

The problem is most probably in your loop. I assume it's a pretty standard for loop, in which case such behavior is expected. When you call:

for(var i=0; i<5; ++i) {
  setTimeout(someFunction, 2000);
}

the setTimeout method will be called 5 times in a row in a single moment. This means that someFunction will be called 5 times in a row after 2000 miliseconds.