Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to add a setTimeout on an onclick

I have an add to cart button. When I click on it two things happen at the same time. The class b-items__item__add-to-cart and the onclick.

I would like the onclick to be able to be executed 2 seconds after pressing the add to cart button

With my code it does not work

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<a style="cursor: pointer; margin-bottom: 5px;" data-nom="2001" data-prix="1.10" data-qte="1" data-checkbox="2001" data-url="https://phil.pecheperle.be/image-perles/perle-verre-peche-gardon-2001.JPG" class="btn btn-primary ajouter-panier b-items__item__add-to-cart" onclick="setTimeout(ouvreMaJolieAlert(event), 2000);">add to cart</a>

>Solution :

You’re attempting to give the output of ouvreMaJolieAlert(event) to setTimeout as the callback. The function executes, but the output value of that function is probably nothing, or something else (depends on your specific scenario), meaning that the delayed invocation fails. You’ve probably meant to create a wrapper over it:

setTimeout(() => ouvreMaJolieAlert(event), 2000)

However, personally, I’d recommend you to create a function that handles this from a script; or better yet, use the addEventListener method:

document.querySelector("#the-id-of-your-link-here").addEventListener("click", () => {
   setTimeout(() => ouvreMaJolieAlert(event), 2000));
});

And if you’re planning to create multiple links that will perform this action, you can just replace the ID with a class.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading