Pawan
Pawan

Reputation: 324

Meteor individual user timers - setInterval()

I am building an online quiz system using Meteor. Every use in the quiz is expected to have his own timer set to one hour. The timer is supposed to start when the user first logs in. I am currently maintaining a collection called UserClocks( userId, timeLeft ).

I wrote a setInterval like this

var interval = Meteor.setInterval(function() {

    console.log("User id: " + this.userId);
    console.log("Searching clock for: " + clocksMap[this.userId]); 
    //clocksMap contains the _id of the UserClocks.
    var userClock = UserClocks.find({_id: clocksMap[this.userId]});

    if (!!userClock) {
        console.log("Found clock: " + userClock.timeLeft);
    } else {
        console.log("Clock not found for user: " + this.userId);
    }

    var time = userClock.timeLeft;
    time = time - 1;
    UserClocks.update(userClock._id, {timeLeft: time});
    console.log("Updated userClock. timeleft: " + time);

    if (time === 0) {
        //logout user and clear interval
        Meteor.clearInterval(intervalMap[this.userId]);
    }

}, 1000);

This setInterval() is inside a method which is called b the user. I keep getting timeLeft as NaN as userClock is undefined. I think I understand why I can not use this.userId inside the setInterval(), but I need a solution to my problem. How can I set the timer individually for each user ?

Upvotes: 0

Views: 391

Answers (1)

Andrew Mao
Andrew Mao

Reputation: 36900

Put this code inside a Meteor.methods block. You can use Meteor.userId() inside the setInterval function, but not this.userId. In the callback, this will probably be set to window, which does not have a userId.

If you are running this inside a Meteor.publish callback, store the userId beforehand:

var userId = this.userId;

Meteor.setInterval(function() {
    clock = UserClocks.find({_id: userId});
    // Do stuff
}

The other thing I would recommend, as you see above, is to just store the docs in UserClocks either with _id or userId corresponding to Meteor.userId(). It doesn't make sense to keep a separate map outside of a collection.

Upvotes: 1

Related Questions