Sebastian Hernandez Sebastian Hernandez - 3 months ago 20
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(){
clearTimeout(state.request);
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

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

https://jsfiddle.net/ShinShil/5fw2c63o/

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

function setText() {
    $('#text').append('text');
}