-1

I have a requirement where I need to add delay in between messages.

Imagine the messages as chat messages.var object = [1, 2, 3, 4, 5]; these are the five messages and number 3 is the delay message.

When I reach 3 I need to show typing.. for lets say 2s. and after that 4 and 5 should show.

Here is what I try:

var object = [1, 2, 3, 4, 5];

 for (i = 0; i < object.length; i++) {
                if (object[i] == 3) {   
                    $('div').append('typing');                
                   sleep(2);

                }
                console.log(object[i]);
   }



function sleep(seconds) {
        var waitUntil = new Date().getTime() + seconds * 1000;
        while (new Date().getTime() < waitUntil) true;
    }

My current problem is the div is appending after 2 second not before the delay start.

Why this happen? What is the solution?

Please help Thanks in advance.

Rot-man
  • 18,045
  • 12
  • 118
  • 124

3 Answers3

1

You can use recursive functions (a function that call itself) with setTimeout. Recursion

let numbers = [1, 2, 3, 4, 5, 6, 7, 8]

/*for(let i = 0; i < 10; i++ ) {
  numbers.push(i)
}*/

function doLogic(numbers, index) {
  setTimeout( function() {
      
      if( index >= numbers.length ) { // stop condition
        console.log("DONE")
        return;
      }
    
      /*
       * make logic here
       */
      
      console.log("LOGIC: " + numbers[index] )
      return doLogic(numbers, index+1)
      
  }, 1000 )
}

doLogic(numbers, 0)
0
  1. Created method appendTyping that is executed immediately, passing in the array and index 0
  2. Function executes its logic
  3. At the end, if the next index is still within the bounds of the array, we perform the setTimeout to wait to start the next iteration.

var elements = [1, 2, 3, 4, 5];

(function appendTyping (elements, index) {
  var element = elements[index];
  
  if (element == 3) $('div').append('typing');
  else console.log(element);
  
  if (++index < elements.length) {
    setTimeout(function(){ appendTyping(elements, index); }, 2000);
  }
})(elements, 0);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div></div>
Taplar
  • 24,788
  • 4
  • 22
  • 35
0

Inspired from Tapler ,slight modification here is my answer

var elements = [1, 2, 3, 4, 5,6,7,8];

(function appendTyping(elements, index) {
                var element = elements[index];

                if (++index <= elements.length) {
                    if (element == 3 || element == 6) {
                        $('div').append('typing....');
                        console.log(element);
                        setTimeout(function () { appendTyping(elements, index); }, 2000);
                    }
                    else {
                        $('div').append(index);
                        console.log(element);
                        appendTyping(elements, index);
                    }
                }


            })(elements, 0);