bijus bijus - 3 years ago 176
JSON Question

Show random image with particular time using json array

I am try create signage board application to show ads images,

I have a JSOn array of object with imageurl and it time delay in second, based on this JSON i need to display image one by one with given time delay in page top and bottom div.

Below are my JSON format

{
"topdiv": [
{
"imageurl": "http://lorempixel.com/400/201/",
"timedelay": 1000
},
{
"imageurl": "http://lorempixel.com/400/202/",
"timedelay": 3000
},
{
"imageurl": "http://lorempixel.com/400/203/",
"timedelay": 4000
},
{
"imageurl": "http://lorempixel.com/400/204/",
"timedelay": 1500
}
],
"bottomdiv": [
{
"imageurl": "http://lorempixel.com/1111/111/",
"timedelay": 500
},
{
"imageurl": "http://lorempixel.com/1111/112/",
"timedelay": 1500
}
]
}


I need to show display image in given time delay and show second image in top and bottom div random wise loop never end... using javascript & html ..

Please help me

Answer Source

Check this code.I use setTimout() function and pass it the time parameter that defined after random choose of object elements.The initial time to start is 10ms so in a blinking of eye you will see the images to appear inside the divs.

var data={
"topdiv": [
  {
  "imageurl": "http://lorempixel.com/400/201/",
  "timedelay": 1000 
   },
  {
  "imageurl": "http://lorempixel.com/400/202/",
  "timedelay": 3000 
   },
  {
  "imageurl": "http://lorempixel.com/400/203/",
  "timedelay": 4000 
   },
  {
  "imageurl": "http://lorempixel.com/400/204/",
  "timedelay": 1500 
   }
],
"bottomdiv": [
  {
  "imageurl": "http://lorempixel.com/1111/111/",
  "timedelay": 500
   },
  {
  "imageurl": "http://lorempixel.com/1111/112/",
  "timedelay": 1500
   }
]
};
var topImg=data.topdiv;
var botImg=data.bottomdiv;
var topDivImg=document.getElementById('topImg').children[0];
var botDivImg=document.getElementById('botImg').children[0];
    var time=10;
    var imge_1=function (){
    var elm_1=topImg[Math.floor(Math.random()*topImg.length)];
    topDivImg.src=elm_1.imageurl;    
    var time=elm_1.timedelay;
    setTimeout(imge_1,time);
    };
    setTimeout(imge_1,time);
    
    var imge_2=function (){
    var elm_2=botImg[Math.floor(Math.random()*botImg.length)];
    botDivImg.src=elm_2.imageurl;    
    var time=elm_2.timedelay;
    setTimeout(imge_2,time);
    };
    setTimeout(imge_2,time);
<div id="topImg"><img src="" alt=""></div>
<div id="botImg"><img src="" alt=""></div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download