Date in Javascript Div loop not updating correctly - javascript

I'm trying to generate 3 divs in a for loop and insert the datetime in each iteration . The problem I'm running into is while the function generates the three div's correctly it appends the same time to all 3 div's leaving me (JavaScript newbie) to believe the Date() function is only being executed once . If any we could explain to me what is going on I would greatly appreciate it. Ideally I would like to replace the Date function with graph's and have a graph load in each div.
function gengraphs () {
for (i=0; i < 3; ++i) {
var divTag = document.createElement("div");
divTag.style.width ="1000px";
divTag.style.height ="600px";
divTag.id = "graph"+i;
document.body.appendChild(divTag);
divTag.innerHTML = Date();
// divTag.appendChild(getGraph(divTag));
// divTag.innerHTML = getGraph(divTag);
}
}

The server is executing the script fast enough (in milliseconds) that the date() returned is not visibly different. Try something to delay or use the increment variable i

The loop is being executed so quickly that you won't see a difference in time. Try calling the contents of your loop with a significant delay (e.g. 1s) and put it into a function as shown here: JavaScript sleep/wait before continuing

Related

javascript code hanging the page

I am trying to get the position of a moving div(animated using css3 animations) and for checking it continuously I am using a while(true) like below
function detectCollision(){
alert(document.getElementById("obstacle").style.left)
while(true){
var temp = getObstaclePosition();
var temp2 = getPlanePosition();
if(temp[0] <= temp2[0]+500){
document.getElementsByClassName("plane")[0].style.display = "none";
break;
}
}
}
The problem here is that after the first alert the page hangs. Moreover if I put an alert in the while loop then it keeps on popping up and the code works fine but not otherwise.
Let me know how I can fix this?
Instead of using a while (true), which is costly, you can use setInterval:
a = setInterval(function () {
var temp = getObstaclePosition();
var temp2 = getPlanePosition();
if(temp[0] <= temp2[0]+500){
document.getElementsByClassName("plane")[0].style.display = "none";
clearInterval(a);
}
}, 100);
The page does not render while you are inside that loop, and thus the position of the element will not change. This results in the loop never ending.
If you want to do something like this, you will have to be using a recursive setTimeout or a normal setInterval implementation.
With them, do one check per timeout.
https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout
JavaScript runs in one and the same thread, so if some loop occupies this with an infinite loop, the rest is not able to run anymore.
As an alternative to your loop, you could use setInterval, which repeatedly executes a function or code snippet:
setInterval(new function() {
// whatever
}, 100); // repeat every 100 ms, i.e. 10 times per second

Sprite Animation using a for loop

I am trying to create an animation using a sprite sheet and a for loop to manipulate the background position until it has reached the total number or rows in the sheet. Ideally a reset back to the initial position would be practical, but I cannot even get the animation itself to trigger...
With the current function, no errors occur and the background position in my CSS does not change. I even recorded using Chrome DevTools Timeline and there was nothing either then everything related to my page loading. I have also tried using "background-position-y" as well as a simpler value rather then the math I currently have in place.
This is my function:
$(document).load(function() {
var $height= 324;
var $rows= 34;
for(var i=0; i<$rows; i++){
setTimeout(function() {
$('#selector').css("background-position", "0px ", "0" - ($height*i) + "px");
}, 10);
}
});
I hate to ask a question that is similar to previous issues, but I cannot seem to find another individual attempting sprite sheet animation with a for loop, so I suppose it is it's own problem.
p.s. I didn't include a snippet of my HTML and CSS because it is pretty standard and I don't see how that could be the problem. That being said, I am all ears to any potential thoughts!
I am completely revamping my answer
This issue is that the for() loop is not affected by the setTimeout so the function needs to be written on our own terms, not with a loop
Working Fiddle
Here it is..
var $height= 5;
var $rows= 25;
var i = 1; // Starting Point
(function animateMe(i){
if(i<=$rows){ // Test if var i is less than or equal to number of rows
var newHeight = 0-($height*i)+"px"; // Creat New Height Position
console.log(i); //Testing Purposes - You can Delete
$('#selector').css({"background-position": "0px "+ newHeight}); // Set New Position
i++; // Increment by 1 (For Loop Replacement)
setTimeout(function(){animateMe(i)}, 1000); // Wait 1 Second then Trigger Function
};
})(0);
Here is your solution
First Change
$(document).load() To $(document).ready()
And Change .css Syntex as
$('#selector').css("background-position",'0px '+(0 - ($height*i))+'px');
Here is fiddle Check it ihad implemented it on my recent project http://jsfiddle.net/krunalp1993/7HSFH/
Hope it helps you :)

Making a function that adds a number to a variable every second in Javascript

Hey so basically I want to create a function that at every 1 second adds 1 or a changeable number to another variable.
I have been searching the internet for this but haven't been able to find it. I am guessing that it should be fairly simple.
var counter =0;
var value = 1; //the number to add. You can change it by modifying the variable
setInterval(function() {
counter+= value;
},1000);
but, if you want to add 1 per second, a much more efficient way would be
//set the initial value
var start = Date.now();
//create a function you can call anytime to get the diff
function getCurrentDiff() {
return (Date.now() - start)/1000;
}
then you don't have to be constantly running the add function, which gets expensive over time.
setInterval or setTimeout?
setTimeout(function(){number++;},1000);
or
setInterval(function(){number++;},1000);

how to stop moving background-image position

I've background image and by using small javascript code, it moves from right to left.
HTML code
<div id="clouds_image"></div>
Javascript code
var g=0;
var speed=30;
function rollClouds() {
document.getElementById('clouds_image').style.backgroundPosition=g+'px 0';
g--;
scroller=setTimeout(function(){rollClouds()},speed);
}
window.addEventListener?
window.addEventListener('load',rollClouds,false):
window.attachEvent('onload',rollClouds);
But i've noticed that, with time my PC CPU memory usage increased ! causing overload on my pc and if i disabled that javascript code, it back to normal.
My question
so i think i need to modify this javascript code that it not keep working forever, i mean, i want to make it to repeat that action only 5 times then stop , maybe i need to define value of g but i'm not good in javascript so any help ~ Thanks.
You need to use a variable to count how many times that function was executed, and use setInterval instead of setTimeout: See example
http://jsfiddle.net/EQDjx/206/ (my counter start from 100 and goes down to 0)
for a more nice effect i recomand you to use jquery. See animate function
http://api.jquery.com/animate/
var g = 1000;
var speed=300;
var counter = 100;
function rollClouds() {
document.getElementById('clouds_image').style.backgroundPosition=g+'px 0';
g--;
if (counter < 1) clearInterval(interval);
}
interval = setInterval(function(){rollClouds()}, speed)
A cleaner solution might be to use jQuery to move the background:
function moveClouds() {
$("#clouds_image").css({left:"-2000px"});
$("#clouds_image").animate({left:"2000px"},10000);
}
Then you might set an interval to trigger it every x milliseconds.
setInterval(moveClouds,10000)
JSFiddle is here: http://jsfiddle.net/qXpVX/

How to make a variable timer sequence which runs infinitive

I have n parameters which have to be run in sequence for t seconds each. All the data is stored in an array which is loaded dynamically through ajax and json and exists of: function parameters p and time to sleep t
function(p1), for 30 seconds; when it completes function(p2) for 15 seconds etc etc
Until the array is complete; then we have to start all over.
The number of parameters and its time being displayed are not determined on forehand.
How can I implement this with javascript?
//edit:
I tried to make one big function with function(p1) starting at t=0; function(p2) starting at t=t1; function(p3) starting at t=t1+t3
But it felt 'stupid' and overdone....
I suspect you array looks like
var myarray=[['p1',30],['p2',15] ...];
In this case you could
function runme(i) {
if (i>=myarray.length) i=0;
var p=myarray[i][0];
var t=myarray[i][1];
myfunction(p);
i=i+1;
window.setTimeout('runme('+i+');',1000*t);
}
Edit
And ofcourse
runme(0);
to start.

Categories