Javascript for loop problems - javascript

So I have the following code which i basically just a JSON string I am using eval to convert to an object. Now, this object has an array of elements that gets displayed to the screen via a for loop:
function DisplayListing(str)
{
var obj = eval("(" + str + ")");
var div = document.getElementById('Response');
for(i=0; i<obj.files.length; i++)
{
div.innerHTML += '<span id="listing' + i + '" class="displayNone"><img src="' + obj.files[i].icon + '"/>' + obj.files[i].name + '</span><br />';
}
}
This works just fine. However, what I want it to do is wait a set interval of time before it continues to the next element. I want to it basically call a function with a timeout, so each element fades onto the screen individually. All attempts so far on cause the last element to execute a function. Any help would be greatly appreciated!

http://jsfiddle.net/SfKNc/
var obj = {files: [1, 2, 3]}; // sample object - use JSON.parse by the way
var div = document.getElementById('Response');
for(var i=0; i<obj.files.length; i++) { // use var!
setTimeout((function(i) {
return function() { // i changes, so create a new function in which i does not change
div.innerHTML +=
'<span id="listing' + i +
'" class="displayNone">' + i +
'</span><br />';
};
})(i), i * 1000); // set timeout to 1000 ms for first item, 2000 for second etc.
}

you have manually create a sleep function something like the below:
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
or you create an empty function and use the setTimeout on it
function sleep()
{
setTimeout(Func1, 3000);
}
Func1(){}
http://www.phpied.com/sleep-in-javascript/

Related

Assign id to div dynamically created from a JSON file

I want to assign dynamic id attributes to the div(s) which are being appended through JavaScript. For example:
function x() {
for (current_list = 0; current_list < data.length; current_list++) {
$("#current").append(
"<div class="card">" +
"" + data[current_list].name + "" +
"</div>");
}
}
Two cards will be appended, so I want to assign them an id which can increase if there are more numbers of arrays present in the JSON.
you probably looking for this.
function x() {
var container=$("#current");
for(var i=1;i<10;i++)
{
var id="card"+i;
var divHtml="<div class='"+id+"'>" +
""+data[current_list].name+"" +
"</div>"
container.append(divHtml);
}
}
As Rory said, here a solution using DOM traversal.
You would have to call this after appending your "cards".
$(".card").each(function(value, index){
$(value).attr("id", "card" + index);
});
if you call x() function one time you can use
function x() {
for (current_list = 0; current_list < data.length; current_list++) {
$("#current").append('<div id="card-'+current_list+'" class="card">' + data[current_list].name + '</div>');
}
}
and if you call it many time you can use this function after every call
$(".card").each(function(value, index){
$(value).attr("id", "card-" + index);
});

Issue when trying to use jQuery's window.open function in combination with a for-loop to iterate through an array

Let's say I have an array of links like this:
var playlist = [
"",
"https://www.youtube.com",
"https://www.google.com",
"https://www.facebook.com",
"https://www.instagram.com"
];
And a bunch of boxes generated in the following way:
for(var i = 1; i < 5; i++) {
$(".container").append("<div class='luke luke-" + i + "'>" + "<h3 class='nummer'>Luke " + i + "</h3> " + "</div>");
}
I then want to iterate through this array to open a specific link when a box is clicked.
for(var i = 1; i < 5; i++) {
$(".luke-" + i).click(function(){
window.open(playlist[i], "_blank");
})
}
That doesn't seem to work at all, however the example below does exactly what I want.
$(".luke-1").click(function(){
window.open(playlist[1], "_blank");
})
$(".luke-2").click(function(){
window.open(playlist[2], "_blank");
})
$(".luke-3").click(function(){
window.open(playlist[3], "_blank");
})
$(".luke-4").click(function(){
window.open(playlist[4], "_blank");
})
$(".luke-5").click(function(){
window.open(playlist[5], "_blank");
})
So this works, but it's a pain in the ass to setup as I want to have 25 boxes in total and this solution offers little to no flexibility if I want to increase or decrease that amount at a later time. What am I doing wrong with the for-loop that's causing issues here?
If I use
console.log(playlist[i]);
inside of the for-loop, it simply returns "undefined" regardless of what box I click in case that helps.
You can do this much easier and simpler using a data attribute.
HTML
<div class="container"></div>
Javascript/jQuery
var playlist = [
"",
"https://www.youtube.com",
"https://www.google.com",
"https://www.facebook.com",
"https://www.instagram.com"
];
for(var i = 1; i < 5; i++) {
$(".container").append("<div class='luke' data-url='" + playlist[i] + "'>" + "<h3 class='nummer'>Luke " + i + "</h3> " + "</div>");
}
$('.luke').click(function() {
window.open($(this).data('url'));
});
Demo Here
You are not doing right.
EXAMPLE FIDDLE
var playlist = [
"https://www.youtube.com",
"https://www.google.com",
"https://www.facebook.com",
"https://www.instagram.com"
];
var container = $("#container");
for(var i = 1; i < 5; i++) {
container.append('<div class="luke" db-id="'+ i + '"><h3 class="nummer">Luke ' + i + '</h3></div>');
}
$(".luke").click(function(i){
window.open(playlist[$(this).attr('db-id')], "_blank");
});
for(var i = 1; i < 5; i++) {
$(".luke-" + i).click(function(i){
window.open(playlist[i], "_blank");
})
}
The click event will launch your function only inside the scope of the loop. This means that once the loop have finished, ( and counting from 0 to 5 is insanely fast for your computer ) there's no more function attached to your click event. In other terms, as long as i < 5, your click function will work as you expect, but after that, the click event will no longer call the function you created.
One solution could to be attach a function to the onclick attribute in the HTML like this :
for(var i = 1; i < 5; i++) {
$('<div/>', {
'class': 'luke luke-' + i,
'click': yourFunction(i)
}).appendTo(${'.container'});
$('<h3/>', {
'class':'nummer',
'html': 'Luke' + i
}).appendTo(${'.luke-'+i})
}
and then write a function like this :
function yourFunction(index){
window.open(playlist[index], "_blank");
}
Simple way by using Hyperlink
hyperlinks
Demo Here

How to iterate elements over time in jquery

I'm working on this automated, non-endless slideshow, with dynamically loaded content. Each image has to be acompanied by sound. So far I got dynamic loading of both images and sounds down. But it all happens at once, which it shouldn't. I figured, that setTimeout can come in handy here, to set the interval between each pair, but all I got is either last image multiplied by the iteration count or script not working at all. delay also didn't prove to be of any help.
Here's whot I got so far:
function displayImages(data){
var count = data;
var pixBox = $('#picture-box');
var imgPre = 'resources/exhibit-';
var imgExt = '.png';
var sndExt = '.wav';
for(i = 1; i < count; i++) {
var imgSrc = '<img src="' + imgPre + i + imgExt + '">';
var sndSrc = new Audio(imgPre + i + sndExt);
sndSrc.play();
pixBox.append(imgSrc);
}
}
My question is: how to set the setTimeout (or whatever function is the best here), for it to iterate over time. Say, to set the change of img/sound pairs every 2 seconds?
You can use setTimeout like this:
function displayImages(cur, total){
var pixBox = $('#picture-box');
var imgPre = 'resources/exhibit-';
var imgExt = '.png';
var sndExt = '.wav';
var imgSrc = '<img src="' + imgPre + cur + imgExt + '">';
var sndSrc = new Audio(imgPre + cur + sndExt);
sndSrc.play();
pixBox.append(imgSrc);
return setTimeout( 'displayImages(' + ((cur+1)%total) + ',' + total + ')', 2000 );
}
And start it off like this: displayImages(0,total) where total corresponds to your data variable.
The reason I like to use setTimeout and not setInterval in these situations is that setTimeout is only called after the previous function has completed. setInterval can get back-logged and freeze up your page.
Note that the function returns a handle for the timeout. If you should want to stop the animation, you can do this:
var animation = displayImages(0,total);
...some code...
clearTimeout(animation);
and the animation will stop.
You can use a setInterval, this does the same code at every interval.
var myInterval = window.setInterval(displayImages, 2000);
This will make sure your function gets called every 2000 milliseconds.
More information on MDN setInterval
You can try something like this
$(function() {
var count = 100;
var i = 0;
var repeat = setInterval(function() {
if (i <= count) {
var imgSrc = '<img src="' + imgPre + i + imgExt + '">';
var sndSrc = new Audio(imgPre + i + sndExt);
sndSrc.play();
pixBox.append(imgSrc);
i++;
}
else{
i = 0; //reset count if reaches threshold.
}
}, 5000); //5 secs
});
With this, if you want to reset the interval on any event you can simple call
clearInterval(repeat);
See a setInterval example here: JSFiddle
var i = 0;
setInterval(fadeDivs, 3000);
function fadeDivs() {
i = i < images.length ? i : 0;
$('#my-img').fadeOut(200, function(){
$(this).attr('src', images[i]).fadeIn(200);
})
i++;
}

Get argument of executed function in function Javascript

I have a function that measures time execution of function, and cleans DOM after each execution:
function measureTimeExecution(domID, testFunc){
console.time("timer");
for(var i = 0; i < 10; i++){
testFunc();
var getDiv = document.getElementById(domID);
}
getDiv.empty();
console.timeEnd("timer");
}
Function that creates new ul
function createList_Task_2(divID){
var createNewUL = document.createElement("ul");
createNewUL.id = "phoneList";
document.getElementById(divID).appendChild(createNewUL);
for(var i = 0; i < phones.length;i++){
var chunk = "<li>" + phones[i].age +"<br>" + phones[i].id +"<br><img src='"
+ phones[i].imageUrl +"'/><br>" + phones[i].name + "<br>" + phones[i].snippet + "</li>";
document.getElementById("phoneList").innerHTML += chunk;
}
}
But iy gives me: Uncaught TypeError: testFunc is not a function;
Example:
measureTimeExecution("div1", createList_Task_3("div1"));
Is it possible to get somehow domID in measureTimeExecution as a argument of testFunc?
the problem is that when you are calling measureTimeExecution you are runing the parameter, instead pass a function again.
look at this code it should work
measureTimeExecution("div1", function () { createList_Task_3("div1"); });
function measureTimeExecution(domID, testFunc)
The function expects the second argument to be a function, but calling it like measureTimeExecution("div1", createList_Task_3("div1"));, it provides the return of createList_Task_3("div1"). Since createList_Task_3 returns nothing, the default return is undefined.
For it to be a function as well as be able to be provided the ID, it should return a function like this:
function createList_Task_2(divID){
return function(){
var createNewUL = document.createElement("ul");
createNewUL.id = "phoneList";
document.getElementById(divID).appendChild(createNewUL);
for(var i = 0; i < phones.length;i++){
var chunk = "<li>" + phones[i].age +"<br>" + phones[i].id +"<br><img src='"
+ phones[i].imageUrl +"'/><br>" + phones[i].name + "<br>" + phones[i].snippet + "</li>";
document.getElementById("phoneList").innerHTML += chunk;
}
}
}

Why this setTimeout() methods not working in this function?

function SlideShow(area)
{
var SlideImg = new Array('img1', 'img2');
var SlideArea = document.getElementById(area);
for(i=0;i<SlideImg.length;i++)
{
var html = '<img src="images/room/' + SlideImg[i] + '.jpg" id="' + SlideImg[i] + '" class="not-active" />';
SlideArea.innerHTML += html;
}
var a = 0;
function RunSlide()
{
document.getElementById(SlideImg[a]).className = 'active';
a++;
}
var run = setTimeout('RunSlide()', 5000);
}
This function not working after I add the setTimeout() method there. Can anybody help me?
Just change it to:
var run = setTimeout(RunSlide, 5000);
The reason is: when you pass a string to setTimeout() it is evaluated in global context - where RunSlide is not visible, because it is local.
Passing a string to setTimeout() is never a good idea, here you have one reason.

Categories