Home > Back-end >  Using setTimeout function not working in React
Using setTimeout function not working in React

Time:07-07

am trying to use the setTimeout function if the user clicks on the button, I want it to display successfully for just 3sec, it displaying but it's not executing the 3sec time given. what am I doing wrong?

Here’s my code

const [message, setMessage] = useState('')

  function handleSubmit (e) {
    e.preventDefault()

      emailjs.sendForm(process.env.SERVICE_ID,process.env.TEMPLATE_ID, form.current,process.env.PUBLIC_KEY)
    .then(function(response) {
     return setTimeout(setMessage("successFully sent"), 3000)
    }, function(err) {
      console.log('FAILED...', err);
    });
  }

CodePudding user response:

you need to use a anonymous function because right now you're calling the function when using setTimeout

const [message, setMessage] = useState('')

  function handleSubmit (e) {
    e.preventDefault()

      emailjs.sendForm(process.env.SERVICE_ID,process.env.TEMPLATE_ID, form.current,process.env.PUBLIC_KEY)
    .then(function(response) {
     return setTimeout(() => setMessage("successFully sent"), 3000)
    }, function(err) {
      console.log('FAILED...', err);
    });
  }

CodePudding user response:

setTimeout(func,n) executes func after n milliseconds.

If you want the message to be displayed during 3s,

  1. Set the message immediately
  2. Clear the message after 3s.

Inside your then callback,

setMessage('successfully sent'); 
setTimeout(()=>{ // may start timer before message is set.
    setMessage('')
}, 3000);

However due the asynchronous nature of state updates, the setTimeout may be "set" before the success message, resulting in the message for being shown for, example 2.993 seconds.

A more precise solution would be:

handleSubmit=(evt)=> { // arrow functions preserve 'this' of component
    // ....
    .then((response)=> {
         this.setState({message: 'Successfully sent'}, ()=> {
             setTimeout(()=> { // start timer after the message is set
                 this.setState({message: ''}); 
             }, 3000);
         }); 
    })
    // ...
} 

Here the 2nd callback argument of setState is run, after message is set.

  • Related