Accessors can use the setInterval() function to schedule periodic events. setInterval() takes a callback function and milliseconds as arguments. Any further arguments will be passed to the callback function.
Here, we'll create a camera that takes a snapshot every five seconds. Periodic events can continue indefinitely, or can be canceled by saving the returned handle and invoking clearInterval(handle).
Click 'react to inputs'. The camera should start taking snapshots every five seconds, stopping after one minute.
Next, make duration and interval parameters to control the camera.
/** An accessor that takes a snapshot every five seconds for a minute.
* @accessor tutorial/TimedCamera.
* @input start Start taking snapshots.
*/
exports.setup = function() {
this.input('start', {'value' : true});
this.camera = this.instantiate('Camera', 'cameras/Camera');
this.camera.setParameter('triggered', true);
};
exports.initialize = function() {
var self = this;
var interval = 5000, duration = 60000, elapsed = 0;
var handle = null;
this.camera.send('trigger', true);
// Upon start, trigger the camera every 5 seconds for 60 seconds total.
this.addInputHandler('start', function() {
handle = setInterval(function() {
if (elapsed > duration) {
clearInterval(handle);
}
self.camera.send('trigger', true);
elapsed += interval;
}, interval);
});
};
Modules required: util