In this final (for now, anyway) part of the series, we’re going to look at the approach taken in the Dasher 360 kiosk mode to loop the demo indefinitely (although with variations, as mentioned last time) until someone interrupts by moving the mouse.
The first piece of this is to track the mouse. We do this by attaching an event handler to ‘mousemove’. Here’s the TypeScript code we’re using:
onMouseMove = (event: any): void => {
this._canvasX = event.canvasX || event.clientX;
this._canvasY = event.canvasY || event.clientY;
if (this._startX !== null && this._startY !== null && this._inKioskMode &&
(Math.abs(this._canvasX - this._startX) > this._moveThreshold ||
Math.abs(this._canvasY - this._startY) > this._moveThreshold)) {
this.endDemo();
}
}
You’ll notice we do a little legwork before calling endDemo() (which resets state and sets a flag we check for in the main demo code). This was primarily because a colleague of mine has a very sensitive mouse – which apparently sits on an incline – and so the demo wouldn’t run for long before being interrupted. In fairness, it seemed reasonable to allow for mouse movement below a certain threshold distance to occur without cancelling the demo, so it was good he raised this early on. :-)
In terms of looping the demo, it took me a while to get there, but the following TypeScript code works well.
let loopDemo = (): Promise<any> => {
if (this._inKioskMode) {
return this.performDemo().then(loopDemo);
}
};
Promise.resolve().then(loopDemo).catch((error) =>
console.log('Error: ' + error)
);
It checks the flag that gets set by the endDemo() method, of course, but basically performs a recursive – potentially infinite – loop in a way that works with Promises. I’ve used Array.reduce() to good effect with iterative Promise calls, but that depends on a finite number of enumerable iterations (at least as far as I can tell). The above code works if you just want to keep on going until a certain condition is met.
That’s it for this quick wrap-up of the series. We’re planning on pushing this version of Dasher 360 to production in the coming week or so, so you’ll be able to a) try it for yourself and b) inspect the complete code from the live site.