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/

1
  • 0 -> Math.random()*10000 Commented Nov 18, 2016 at 4:18

3 Answers 3

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);
});
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.