Saturday, 15 May 2010

jquery - Create a time interval that will cause a function to run at a random time in JavaScript -


I am trying to load random images at random times. For some reason this is not making the time random, although it makes the image random. Any ideas what is wrong? var randomTime2 = 3000; // Start the random time with this value to start Interval (function () {var randomNum = Math.floor ((Math.random ()) * 3) +1); // Random Number for Image $ ('Recent Project 2 IMG'). Feedr ('slow', 0, function () {var randomImg = "img / recent-projects -" + randomNum + ".jpg"; $ ('recent-project2img'). Attr ('src', random emg ); $ ('Recent-Project 2 IMG'). Feedto ('slow', 1);}); Random Time 2 = Math.floor (Math.Random (* * 10000); // Reset returns random time 2; // returns random time}, randomTime2);

setInterval will simply append your function and expect expected delay If the duration is over, you need to interval in an internal table to remember to call your code. Although note, even if you change the variable used to specify the interval, its internal table will not be affected: when you call setInterval and it is now archived Then this value has been read.

To make callback time random, give your function a name and use setTimeout instead of setInterval :

  function MyCallback () {. ..setTimeout (myCallback, new_delay); } SetTimeout (myCallback, first_delay);   

With this approach on each call you can set a different delay before the next call.

No comments:

Post a Comment