1

I am planning to make a buttons onClick function automatic after 2 minutes. This is my current button and the function I am calling is handle event videos.

How can I trigger that the button is automatically clicked after 2 minutes. I planned to create a new function and call the handleEventVideos() in there and then pass that function in useEffect. But that doesn't work. Can anyone please help me how I can do this?

                     <Button
                        disabled={isDisable}
                        type="submit"
                        onClick={() => handleEventVideos()}
                        variant="contained"
                        className={classes.doneButton}
                      >
                        Done
                      </Button>
Sinduja
  • 161
  • 11
  • You can use setTimeout() function to automatically trigger after 2 mins SYNTAX : setTimeout(function(){ alert("Hello"); }, 3000); – Gautam Kothari Dec 13 '21 at 04:14

2 Answers2

1

if you want to cal the onclick function in you sample, you can use setTimeout and call handleEventVideos function. It would be something like this:

document.addEventListener('DOMContentLoaded', function() {
  setTimeout(()=>{
    alert("your function of interest!")
  },2000);
});

However, it would be the case if you do not need the event variable in your function (like you example here). However, if you want to invoke the react click event by defining a ref and calling its click function. You can find an extended solution here: How to manually trigger click event in ReactJS? In case you wanted to call it with 2 second delay, you just have to use setTimeout function in the same fashion it is used above.

  • Do you mean like this ? `document.addEventListener('DOMContentLoaded', function() { setTimeout(() => { handleEventVideos(); }, 1000); });` – Sinduja Dec 13 '21 at 04:17
  • Yes, that is the first method I mentioned in the post. It will be executed after one second. – Farshad Kazemi Dec 13 '21 at 04:19
  • I tried that. But it is not executing automatically. I also tried the ref but for typescript it is showing errors. – Sinduja Dec 13 '21 at 04:21
  • Here is a sandbox link to illustrate the first method.: https://codesandbox.io/s/method1-qz8tm I will send another link for the second method as well soon. – Farshad Kazemi Dec 13 '21 at 04:28
  • and here is the link for the second method: https://codesandbox.io/s/method2-7tpio?file=/src/App.js – Farshad Kazemi Dec 13 '21 at 04:32
0

This alert will pop up after 2 minutes. Instead of alert you can put your onclick function there.

const OnClick =()=> {
  setTimeout(()=>{
    alert("I will pop up after 2 minutes")
  },20000);
});
camille
  • 16,432
  • 18
  • 38
  • 60