setTimeout returning undefined in the server


#1

The code snippet below aims to change a document field after 20 seconds and update the another document field separately within a server method.

// Reset the current timeout
    Meteor.clearTimeout(this.timeoutHandle);
    console.log('clearing interval from server');

    // Restart the timeout with a new 10 seconds delay
    var timeoutHandle = Meteor.setTimeout(function () {
      Auctions.update({_id:this._id }, {
        $set: { isOpen: false }
      });
    }, 10000);
     Auctions.update({_id: this._id}, {
      $set: {
        timeoutHandle: timeoutHandle
      }
    });
   
  }

This snippet gets called in the client. The log prints fine and the setTimeout also executes after 10 seconds. but the last updade function doesn’t work. it’s when the console invokes this error exception while invoking method 'doSomething' undefined

doSomething is the name of my server method. The clientside console out the following error message 500 internal server error.


#2

I just see that you are calling this.timeoutHandle
than defining some other timeoutHandle with var
and than calling timeoutHandle without this

other than that code seems OK to me, dont know what is wrong if not scoping


#3

actually when I inserted a document in database, I saved the handler in the timeoutHandle, thus i can get the handler from db. I hope I made my point clear


#4

On server, a timeout handle is an object that cannot be JSONified, so it cannot be saved in a collection (see here, actually this is due to node.js, not Meteor).

However, are you sure you need this? A timeout handle is a session specific piece of data, so storing it in a collection (which is a persistent storage) might not be a good fit.

If you really need to do this, you can create your own handler system:

var myTimeoutHandle = Random.id();
myTimoutHandleMap[myTimeoutHandle] = timeoutHandle 

#5

Actually i’m not quite sure how to associate this custom handler with Meteor.setTimeout. can you please elaborate a bit more.


#6

Here is what I had in mind (using Random for simpler code, but an incremental index would be more efficient) :

Package:

meteor add random

Init:

myHandleMap = {};

Setting the timer:

var myHandle = Random.id();
myHandleMap[myHandle] = Meteor.setTimeout(function () { ... }, 10000);
Auctions.update(this._id, { $set: { timeoutHandle: myHandle } });

Killing the timer:

var myHandle = Auctions.findOne(...).timeoutHandle;
Meteor.clearTimeout(myHandleMap[myHandle]);

#7

That doesn’t help either.