1

I need to teletype a message but I would like a random interval between letters. This is my code for a constant interval:

$( document ).ready(function()
{
  var message = 'Is it possible to create a random interval in javascript?';
  var intervalId = window.setInterval( function ()
  {
    if(message.length>0) 
    {
      setTimeout(function () 
      {
        $("#message_area").append(message[0]);
        message = message.substring(1);
      }, 0);
    }
  }, 150);
});

https://jsfiddle.net/start_florin/7a4yrLzq/

profimedica
  • 2,716
  • 31
  • 41

3 Answers3

3

You can use setTimeout for each round and set the next timer. https://jsfiddle.net/baz7gjed/

$( document ).ready(function()
{

  function writeWord(){
    if(message.length>0){
      $("#message_area").append(message[0]);
        message = message.substring(1);
        window.setTimeout( writeWord, Math.random()*500); //edit your random boundary here
      }
    }

  var message = 'Is it possible to create a random interval in javascript?';
  window.setTimeout( writeWord, 150);
});
weigreen
  • 1,232
  • 8
  • 13
2

You could do something like this: https://jsfiddle.net/gLjgkdyp/1/

I introduce a function to create a random time interval for the setTimeout()

//Create interval between min and max
function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);
}

In your code:

setTimeout(function () 
      {
        $("#message_area").append(message[0]);
        message = message.substring(1);
      }, getRandomInt(10,4000)); //we create a random timeout amount here.
JanR
  • 6,052
  • 3
  • 23
  • 30
1

Could just use jQuery's delay with a random number

$(document).ready(function() {
    var message = 'Is it possible to create a random interval in javascript?';
    $.each(message.split(""), function(i,c) {
     $("#message_area").delay(Math.random() * 500).queue(function (next) {
         $(this).append(c); next()
        });
    });
});
<div id='message_area'></div>
adeneo
  • 312,895
  • 29
  • 395
  • 388