简体   繁体   中英

How do you use javascript to get a random result from an array over a time interval?

I want the function tim below to get an ever changing route from Array every 500 milliseconds. Instead, in my JS console I receive the following repeating error:

VM5550:1 Uncaught SyntaxError: Unexpected end of input

What is going on here and what do I need to do to get the result I'm looking for?

My code:

var Array = ["http://files.parsetfss.com/9.png", 
"http://files.parsetfss.com/5.png",
"http://files.parsetfss.com/6.png",
"http://files.parsetfss.com/7.png",
"http://files.parsetfss.com/8.png"];

var sampl = _.first(_.sample(Array, 1));
var tim = setInterval(sampl, 500);

I also tried wrapping sample in a function like so:

var sampl = function(){return _.first(_.sample(Array, 1))};

I'm still not getting the desired result but now I'm getting a result that is consistently even 7 or 11 (after refeshing the screen a number of times.

First, you should definitely change the name of your var to something else instead of overwriting the Array object.

Next, the _.first seems unnecessary. A sample of 1 is returning a string.

Run the snippet to see the desired effect.

 var arr = [ "http://files.parsetfss.com/9.png", "http://files.parsetfss.com/5.png", "http://files.parsetfss.com/6.png", "http://files.parsetfss.com/7.png", "http://files.parsetfss.com/8.png" ]; var tim = setInterval( function() { document.body.innerHTML = _.sample(arr); }, 500); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.0/lodash.js"></script> 

You need to pass a function to setInterval , whereas you're passing it the result of running your array through underscore's first and sample methods (which in your case is a string). As @Tony points out, the use of first is unnecessary since the second parameter of the sample method specified the number of results you expect (see documentation ).

The following does what I think you're looking for:

var array = ["http://files.parsetfss.com/9.png", 
"http://files.parsetfss.com/5.png",
"http://files.parsetfss.com/6.png",
"http://files.parsetfss.com/7.png",
"http://files.parsetfss.com/8.png"];

function getRandom() {
    return _.sample(array, 1)[0];
} 

function showRandom() {
    console.log(getRandom());
}

// setInterval returns a pointer to the interval ...
var interval = setInterval(showRandom, 500);

// ... which you can use to stop it
//clearInterval(interval);

You can use this function to get random element from array like this:

var url = getRandomeEle(array);

function getRandomEle(arr) {
   return arr[~~(Math.random()*arr.length)];
}

Good answers already and I agree with Tony that you really should change the variable name Array .

I presume you will want to stop this interval at some point in which case you will need to call clearInterval .

Here's a quick DEMO .

script.js

var intervalId,

    startButton = document.getElementById('start'),
    stopButton  = document.getElementById('stop'),

    urls = [
      "http://files.parsetfss.com/9.png", 
      "http://files.parsetfss.com/5.png",
      "http://files.parsetfss.com/6.png",
      "http://files.parsetfss.com/7.png",
      "http://files.parsetfss.com/8.png"
    ];

startButton.addEventListener('click', tim, false);
stopButton.addEventListener('click', stopTim, false);


function tim() {
  intervalId = setInterval(printRandomUrl, 500);
}

function stopTim(){
  clearInterval(intervalId)
}

function printRandomUrl(){
  console.log(_.sample(urls));
}

index.html

<!DOCTYPE html>
<html>

  <head>
    <meta charset="utf-8" />
    <title></title>
    <link rel="stylesheet" href="style.css" />
    <script data-require="jquery" data-semver="2.1.4" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
    <script data-require="lodash.js@3.8.0" data-semver="3.8.0" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.8.0/lodash.js"></script>

  </head>

  <body>
    <h1>Basic plunk!</h1>
     <button id="start">Start</button>
     <button id="stop">Stop</button>

     <script src="script.js"></script>
  </body>

</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM