0

I am trying to set a timer and then return a value when the timer reaches a certain limit. In the code below I need to return the value once the timeElapsed reaches 3.

var timeElapsed = 0;
var interval; 
var ExportApi = {
    tick: function() {
        timeElapsed ++;
        if (timeElapsed == 3) {
            clearInterval(interval);
        }
        console.log(timeElapsed);
    },

    getValues: function() {
        interval = setInterval(this.tick, 1000);
        //Once interval completes return the following values:
        return [{val: '1'}, {val: '2'}]; 
    }
};

module.exports = ExportApi;

//Call get Values
var x = ExportApi.getValues();  
barracuda
  • 968
  • 3
  • 10
  • 26
  • 1
    You mean you want to do something after an interval has fired a certain number of times? You don't return values from `setInterval` - that doesn't make sense. Can you clarify what you're actually trying to achieve? Because presently you're mix-&-matching code that doesn't fit together. – g.d.d.c Nov 25 '15 at 16:10
  • What are you exactly need? This `ExportApi` is unusable at all. Who will clear `timeElapsed` for second use? – vp_arth Nov 25 '15 at 16:12
  • I need to return something after an interval has fired a certain number of times. – barracuda Nov 25 '15 at 16:13
  • Interval functions run asynchronously. How can you return something from it? – Barmar Nov 25 '15 at 16:14

1 Answers1

0

You can't to get synchronous return from asynchronous methods.
Try to learn more about asynchronous javascript, deffers and promises.
With simple and clear addition to your code I return promise-like object:

var timeElapsed = 0;
var interval; 
var ExportApi = {
    tick: function(next) {
        timeElapsed ++;
        if (timeElapsed == 3) {
            clearInterval(interval);
            next();
        }
        console.log(timeElapsed);
    },

    getValues: function() {

        return {
            then: function(fn) {
                interval = setInterval(this.tick.bind(this, function(){
                    fn([{val: '1'}, {val: '2'}])
                }), 1000);
            }
        };

    }
};

module.exports = ExportApi;

//Call get Values
ExportApi.getValues().then(function(x){
    console.log(x);
});

So, when you learn more about real promises, your interface will not change :)

vp_arth
  • 14,461
  • 4
  • 37
  • 66