javascript - setInterval in member function of object error -
i'm trying create throttling queue of sorts in nodejs module. i'm getting error back:
timers.js:265 callback.apply(this, args); ^ typeerror: cannot read property 'apply' of undefined @ wrapper [as _ontimeout] (timers.js:265:13) @ timer.listontimeout (timers.js:110:15)
i'm guessing i'm doing stupid, usual, there reason loses closure scope or when second interval runs?
var queuesvc = function(settings){ var queue = ['bob', 'is', 'name', 'my', 'hi']; var svc = {}; var runtime; svc.addquery = function(queueentry){ queue.push(queueentry); }; svc.stopqueue = function(){ clearinterval(runtime); }; svc.startqueue = function(){ runtime = setinterval(runqueue(queue), settings.queueinterval); }; svc.emptyqueue = function(){ //this method of emptying array needs change //if decide make queue public property queue = []; }; return svc; }; function runqueue(queue){ console.log(json.stringify(queue)); if(queue.length > 0){ var entry = queue.pop(); console.log(entry); } } var = queuesvc({queueinterval: 3000}); it.startqueue();
this common mistake. running runqueue(queue)
, passing return value of setinterval()
. return value undefined
doing this:
runqueue(queue); setinterval(undefined, settings.queueinterval);
this obviously, not want. whenever put ()
after function in runqueue()
means run immediately. function name or definition without ()
after passing function reference can called later.
so, need pass function reference setinterval()
can called later this:
setinterval(function() { runqueue(queue); }, settings.queueinteval);
sometimes people understand bit better when break out named function (not necessary, helpful in understanding going on):
function run() { runqueue(queue); } setinterval(run, settings.queueinteval);
here see passing function reference setinterval()
, letting timer infrastructure call function time later.
the anonymous function in first code block accomplishes same thing. declares second function can pass reference of setinterval()
, when called, calls runqueue(queue)
desired argument.
Comments
Post a Comment