0

I want to send a series of messages through a Messenger bot with some time in between and show the typing effect. Currently I have this code:

      sendTextMessage(recipientId, `Howdy ${snapshot.child("userDetails/firstName").val()}! I’m Marco :)`)
      sendSenderAction(recipientId, "typing_on")
      setTimeout(()=>sendTextMessage(recipientId, "Botting Marco."),1000)
      sendSenderAction(recipientId, "typing_on")
      setTimeout(()=>sendTextMessage(recipientId, "Let me show you some of my recent work. This is the first portfolio bot ever. (afaik) :p"),5000)
      sendSenderAction(recipientId, "typing_on")
      setTimeout(()=>sendTextMessage(recipientId, "How many minutes do you have?"),7000)
      userRef.update({stage:1, class:1, awaiting: true})

However, the typing effect doesn't appear for some reasons. Do I need to use Promises to make sure each line is executed when the previous is finishes? Can you show me an example?

ocram
  • 1,384
  • 6
  • 20
  • 36
  • 1
    no, you don't need to use promises, any sort of callback mechanism will work just as well - promises just make things less messy because they can be chained, so, no "pyramid of doom" or "callback hell" in your code – Jaromanda X Jun 10 '17 at 15:49

1 Answers1

-1

I'm not sure how this will integrate to Facebook, but to get a delayed "typing" effect, you'd want the characters to be typed in an array and then use a timer that increases the delay time as you loop. Promises are not needed to accomplish this.

You need each successive timer to have an increased delay because all the timers that get set up will be "stacked" in the event queue and then they will all execute in rapid succession, creating the text so quickly that it will appear all at once. You need to make sure that each timer waits longer than the previous one did.

Here's an example:

var out = document.getElementById("output");

var message = "This is the text to type...";

// Turn string into proper array so .forEach can be used
var messageArray = Array.prototype.slice.call(message);

// Set the initial stagger amount between timer calls
var stagger = .5;

messageArray.forEach(function(char){
  setTimeout(function(){
    out.textContent += char;
  }, 250 * (stagger++));  // Each timer will have a longer delay on it than the last one
});
<div id="output"></div>

To adapt this to your Facebook use case, you would just replace the contents of the setTimeout function with the call to the Facebook Messenger bot and pass the single character to it.

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71