Refresh, but once

Question:
I have a Socket.io project that, when I send a command (through console), it sends “serverstop” and the users on the website refresh. What happens, though, is that the user refreshes again and again until I restart the project (so chatStopped is false). How can I make them refresh ONCE and then it functions like normal?


Repl link:
https://replit.com/@doxr/TalkRN#index.js

I hope it’s OK that I’m posting a lot of code, I shorted it for this case.

// Check if chat is stopped
let chatStopped = false;

// How I check for the command in this case
process.stdin.on('data', (data) => {
  const command = data.toString().trim();
  if (command === 'serverstop') {
    chatStopped = true;
    console.log('Chat stopped');
  } else {
    console.log('Command not Recognized.')
  }
});

// Some more code and then it goes to this
io.on('connection', (socket) => {
  socket.on('chat message', (msg) => {
    if (!chatStopped) {
      io.emit('chat message', md.render(msg));
    } else {
      io.emit('serverstop');
    }
  });
});

and this is for the browser

// So what happens is that when this serverstop is received, the site basically redirects to itself which is how simulate refreshing
  socket.on('serverstop', function () {
    window.location.replace("https://talkrn.doxr.repl.co");
  });

but the user refreshes again and again, I thought it would happen once. I would appreciate some help!

1 Like

Try to create a separate function to handle stopping the chat, and call this function when you receive the “serverstop” command.

For example:

// Check if chat is stopped
let chatStopped = false;

// Function to stop chat
function stopChat() {
  if (!chatStopped) {
    chatStopped = true;
    console.log('Chat stopped');
    io.emit('serverstop');
  }
}

// How I check for the command in this case
process.stdin.on('data', (data) => {
  const command = data.toString().trim();
  if (command === 'serverstop') {
    stopChat();
  } else {
    console.log('Command not recognized.');
  }
});

// Some more code and then it goes to this
io.on('connection', (socket) => {
  socket.on('chat message', (msg) => {
    if (!chatStopped) {
      io.emit('chat message', md.render(msg));
    }
  });
});

and the browser side:

// So what happens is that when this serverstop is received, the site basically redirects to itself which is how to simulate refreshing
socket.on('serverstop', function () {
  if (!window.location.hash.includes("refreshed")) {
    window.location.replace("https://talkrn.doxr.repl.co#refreshed");
  }
});

There’s a simple check to see if the URL hash contains “refreshed”. If it does, it won’t refresh again.

4 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.