1

While attempting to use setTimeout to perform rate limiting on a monq worker, why is the worker not being throttled?

worker does not wait for 10 seconds before executing setTimeout(). Why is this and how can we get it to delay the call to foo()?

var monq = require('monq')
var client = monq('localhost/mydb')
var worker = client.worker(['general'])
worker.register({
    test: function(params, callback) {
        try {
            setTimeout(foo(params, callback), 10000)
        } catch(err) {
            callback(err)
        }
    }
})

foo = function(params, callback) {
    console.log('Hello world')
    callback()
}
Nyxynyx
  • 61,411
  • 155
  • 482
  • 830
  • Minor point unrelated to your question: http://stackoverflow.com/questions/537632/should-i-use-semi-colons-in-javascript – Evan Trimboli Dec 12 '15 at 05:36

1 Answers1

3

Because setTimeout expects a function reference. Instead, you're executing the function and passing the result to setTimeout.

Use:

setTimeout(function() {
    foo(params, callback);
}, 10000);

Also, the try/catch block is somewhat redundant there, because the call to setTimeout won't throw an exception. Instead, you would need to handle it inside foo.

Evan Trimboli
  • 29,900
  • 6
  • 45
  • 66