Welcome to the Linux Foundation Forum!

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


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



  • 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')
      }, 1000)
      socket.on('data', (data) => {
      socket.on('end', () => { clearInterval(interval) })

    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.


Upcoming Training