Trying to create a function that would create a scheduled post based on time and date

Basically trying to build a message board app that allows users write posts. I want to be able to write posts for the future for example in 5 mins. The problem with this function is that even with setTimeout() and the time difference(seconds) its not working as intended instead its just posting as soon as send the post. I am using firebase and react in this project. messageref refers to the collection!

const sendMessage = async (e) => {
    const now = new Date().getTime()
    console.log(now);
    const seconds = (time - now)/1000
    console.log(seconds);
    e.preventDefault();
    if(formValue === ""){
      alert("must enter a message!")
    }
   
    if(seconds === 0){
      await messageRef
      .add({
        text: formValue,
        timestamp: firebase.firestore.FieldValue.serverTimestamp(),
      })
      setFormValue("")
      pag.current.scrollIntoView({ behavior: "smooth" })
      
    } else if(seconds > 0){
      setTimeout(async () => {
      await messageRef
      .add({
        text: formValue,
        timestamp: time,
      })
      setFormValue("")
      pag.current.scrollIntoView({ behavior: "smooth" })
      }, seconds)
    }else {
      alert('cant send a post in the past')
    }
  };

Answer

The mistake is that you’re passing a value in seconds to setTimeout, while that takes a value in milliseconds. So to fix it:

setTimeout(async () => {
  await messageRef
  .add({
    text: formValue,
    timestamp: time,
  })
  setFormValue("")
  pag.current.scrollIntoView({ behavior: "smooth" })
}, seconds*1000)
//          👆

A longer code snippet:

const time = Date.now() + 5000; // in 5 seconds
const formValue = "Hello world";

const now = new Date().getTime()
console.log(now);
const seconds = (time - now)/1000
console.log(seconds);
if(formValue === ""){
  alert("must enter a message!")
}

if(seconds === 0){
  console.log("Sending now");
} else if(seconds > 0){
  console.log("Sending in "+seconds+"s");
  setTimeout(async () => {
    console.log("Sending now");
  }, seconds*1000)
}else {
  alert('cant send a post in the past')
}

I recommend always reproducing problems in this format, as it makes it easiest for folks to help.