Sebastian Hernandez Sebastian Hernandez - 1 year ago 75
Javascript Question

How to delay a function excecution

I have this situation, i'm building a shopping cart, and i need to make a http request each time a product is added or its quantity is changed.

I have one button to add 1 unit of a product to the cart, it supposed that each unit added should make the http request, but i want to avoid to make to many calls at once... So i wanted to set a timeout for the request, but if within 3 secs the user clicks again, then i should cancel the last request with old data and then set a new timeout fot the request with the new data.

So i came up with this solution

function doRequest(){
state.request = setTimeout(updateCartService, 180);

The function is inside another function that retrieves the state object (A collection of variables and data persistent through all the application). The updateCarteService function contains the http request.

However all the requests are still being made, if i click 5 times the button that triggers doRequest, the call i being excecuted 5 times.

Have any idea of what could be wrong or pherhaps a better aproach to achieve my goal?

If it helps i'm bulding the site using vueJs, vuex (flux) and this code is inside an action.

Answer Source

setTimeout takes milliseconds, so you set timout for 180ms, it is too short, try 3000 for example. Here a small jsfiddle example.

var timeout;
$('#click').click(function() {
  timeout = setTimeout(setText, 3000);

function setText() {