I'm working on a project using node.js. I'm pulling in a chunk of JSON data and I need to schedule jobs to write data out a serial port based on the data received. I'm using node-schedule for this task. There are several jobs that need to be scheduled and the command for each one is different. What I'm finding is that the arguments passed to the function within the scheduleJob
call are interpreted at execution time rather than when scheduled within the for loop. Any ideas on how I can get the string argument to be constant?
Code Example:
var schedule = require('node-schedule');
var schedules[];
…
var startrule = new schedule.RecurrenceRule();
var start_hour = thejson.start_hour;
var start_minute = thejson.start_minute;
for (var k = 0; k < thejson.zones.length; k++)
{
//start
startrule.hour = start_hour;
startrule.minute = start_minute;
var start = schedule.scheduleJob(startrule, function(){
writeSerial('//S' + thejson.zones[k].number + ',1');
});
schedules.push(start); //upon next json update, old schedules in array are cancelled.
}
When it executes, thejson.zones[k].number
fails because k
is unknown. How can I get that string argument to writeSerial()
to be static/constant? I've tried sticking it in an array and passing an index to writeSerial
within the schedule, but that index variable is also interpreted at schedule execution.