Welcome to the Linux Foundation Forum!

setInterval timer doesn't end - example-server.js

Hello,

In "working with streams" chapter, the example-server.js has clearInterval(interval), this code doesn't seem to end the setInterval invocation. Both server and client has been started as described in the module.

I am on node v10.22.1

Regards
Mohan

Answers

  • davidmarkclements
    davidmarkclements Posts: 270
    edited December 2020

    hey @mohankumaryum I'm not sure if you're perhaps confused by the server process staying open, the interval does indeed clear. The server process stays open because the net.createServer function keeps it open so it can accept connections.

    If we add a log line into the server code like so:

    'use strict'
    const net = require('net')
    net.createServer((socket) => {
      const interval = setInterval(() => {
        console.log('SERVER beat')
        socket.write('beat')
      }, 1000)
      socket.on('data', (data) => {
        socket.write(data.toString().toUpperCase())
      })
      socket.on('end', () => { clearInterval(interval) })
    }).listen(3000)
    

    You'll see the interval is called 3 times and then stops, because it's cleared after 3250ms a a result
    of the client closing the socket.

Categories

Upcoming Training