简体   繁体   中英

Using setTimeout function not working in React

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);
    });
  }

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);
    });
  }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM