Search code examples
javascriptjqueryasynchronouspromisechaining

How to chain two counter functions so they occur sequentially using javascript/jquery?


I would like to run two functions sequentially, such that the first function runs, and then the second function runs after. Usually I can do this by simply calling the first function first and use it's result for the second function

See below for my code and here for my codepen

function add_count(i){
  document.body.appendChild(document.createElement('pre')).innerHTML = i
}

function count_three_up(i){
  setTimeout(add_count,1000,i)
  setTimeout(add_count,2000,i+1)
  setTimeout(add_count,3000,i+2)
  return i + 3
}

next_number = count_three_up(1)//first function
count_three_up(next_number)//second function

The result of this produces:

1, 4, 3, 5, 3, 6

However I'd like to produce

 1,2,3,4,5,6

I should mention that it's important that the second function uses the result from the first function.


Solution

  • You could take different value to add, because you have different times for timeout.

    What you have is

    time   1000  2000  3000
    values    1     2     3
              4     5     6
    

    but you need

    time   1000  2000  3000
    values    1     3     5
              2     4     6
    

    That means, you need to return only a value incremented by one instead of three.

    function add_count(i){
        document.body.appendChild(document.createElement('pre')).innerHTML = i;
    }
    
    function count_three_up(i){
        setTimeout(add_count, 1000, i);
        setTimeout(add_count, 2000, i + 2);
        setTimeout(add_count, 3000, i + 4);
        return i + 1;
    }
    
    next_number = count_three_up(1);
    count_three_up(next_number);