Skip to Content
Polling

Polling Ticker Example

Demonstrates infinite server polling ticker in a while(true) loop that’s used to reconnect when the connection is safely closed by the server. The client-side sends i parameter to the server-side in a query, the server increments it and streams the result back to the client. After 10 iterations, the server ends the response and the client starts polling again. Open devtools to see network requests.

Result

Poll Ticker

0

Code

src/modules/polling/PollController.ts
import { get, prefix } from 'vovk'; import { withZod } from 'vovk-zod'; import { z } from 'zod'; @prefix('polling') export default class PollController { @get('', { cors: true }) static streamPollResponse = withZod({ query: z.object({ i: z.string(), }), iteration: z.object({ i: z.number(), }), async *handle(req) { let i = parseInt(req.vovk.query().i); while (true) { yield { i: ++i }; await new Promise((resolve) => setTimeout(resolve, 1000)); if (!(i % 10)) { break; } } }, }); }

The code above is fetched from GitHub repository. 

Last updated on