java script Foreach loop - javascript

Javascript
function myFunction() {
for (i = 0; i < 5000;) {
setTimeout(function() {
document.getElementById("demo").innerHTML = i;
}, i);
i += 500;
}
}
HTML
<body onload="myFunction()">
<div id="demo"></div>
How to increase " i " every 5ms and print it in #demo every time it changes
I am trying to make a look that increases the value of ( i ) once every 5ms, and prints it out in # demo.
Right now, the value 5000 immediately prints out as soon as I run the script for some reason, as opposed to increasing by 500 every time.
Thanks in advance.

You can change myFunction to:
var i = 0;
function myFunction() {
var timerId = setInterval(function(){
if(i >= 5000)
{
clearInterval(timerId);
}
document.getElementById("demo").innerHTML = i;
i +=500;
}, 5);
}

this should work.
var i=0;
function looper(){
setTimeout(function(){
console.log(i+" data");
i=i+500;
if(i<5000)
looper();
}, i);
}
looper();

function myFunction() {
var i = 0;
var max = 5000;
var step = 500;
var intervalMs = 5;
var interval = setInterval(function() {
// clear interval if one step before max value
if (i >= max-step) {
clearInterval(interval);
}
// increment i by step
i+=step;
// set inner html of div
document.getElementById("demo").innerHTML = i;
}, intervalMs)
}
Plunkr: https://plnkr.co/edit/IfkGOpjUnf4sKpN4iCZ4?p=preview

If you want your code to look similar to what you have, you can use an IIFE:
function myFunction() {
for (i = 0; i <= 5000;i += 500) {
(function(index) {
setTimeout(function() {
document.getElementById("demo").innerHTML = index;
}, index);
})(i);
}
}
<body onload="myFunction()">
<div id="demo"></div>
</body>

You are having an issue with the closure not saving a reference to your timeout. Subsequent arguments after the second are passed into the callback function as arguments.
Here we are passing i as the third argument
setTimeout(fn, delay, i)
Then in the callaback we have access to the i, we are reassigning it to x within the scope of the callback.
function myFunction() {
for (i = 0; i <= 5000; i = i + 500) {
setTimeout(function(x) {
document.getElementById("demo").innerHTML = x;
}, i, i);
}
}
myFunction()
<div id="demo"></div>
function myFunction(max, ii = 0) {
document.getElementById('demo').innerHTML = ii
if (ii < max) {
setTimeout(myFunction, 500, max, ii + 500)
}
}
myFunction(5000)
<div id="demo"></div>

**
<div id="demo"></div>
<script>
function myFunction() {
var i = 0;
var setClock = function() {
if (i < 5000) {
local = i;
i += 500;
setTimeout(function() {document.getElementById("demo").innerHTML = local; setTimeout(setClock, 500);},
500);
}
}
setClock();
}
**
you should wrap scripts in tags
the javascript Closures. You should know that because of the Closures, second parameters for all setTimeout() are 5000, which is the i's final value. You can avoid the Closure by the codes I showed or erase the impact of Closure by below codes:
<div id="demo"></div>
<script>
function myFunction() {
var local;
for (i = 0; i < 5000; i+= 500) {
local = i;
setTimeout((function(interval){
return function() {document.getElementById("demo").innerHTML = interval;} ;
})(local), (function(interval){return interval})(local));
}
}

Related

Recursion with arguments method

The script must have to print 'Hello', then 'Good bye', because of the entries on function call. But only prints once. Why?
What's wrong here bellow.
PD: Now it doesn't work. It does if i comment the recursion call line
<html>
<head>
</head>
<body>
<script type="text/javascript">
function writing(i,first,second) {
len=arguments.length;
if (i<=len) {
current=arguments[i];
c=0;
inter=setInterval(function() {
if (c>=current.length) {
clearInterval(inter);
} else {
field=document.getElementById('div1');
field.innerHTML+=current[c];
c+=1;
}
},200);
}
i<len?writing(i+1,first,second):writing(i=0,first,second);
}
writing(1,'Hello','Good bye');
</script>
<div id="div1"></div>
</body>
There are so many problems with the code , first was it was infinite loop (never ending) , second was variable declaration , and others...
Here I have attached the snippet , please run and check, if its that you are looking for.
I have to add setTimeout for fullfill your requirement.
var interval_counter = 0;
function writing(i, first, second) {
var len = arguments.length;
if (i != 0 && i <= len) {
var current = arguments[i];
var c = 0;
setTimeout(function() {
var inter = setInterval(function() {
if (c >= current.length) {
clearInterval(inter);
} else {
field = document.getElementById('div1');
field.innerHTML += current[c];
c += 1;
}
}, 200);
}, 200 * interval_counter);
interval_counter = interval_counter + current.length;
i < (len - 1) ? writing(i + 1, first, second) : writing(i = 0, first, second);
} else {
return false;
}
}
writing(1, 'Hello', 'Good bye');
<div id="div1"></div>

Confused about SetInterval and closures

How can we repeatedly update the contents of a div using setInterval
I am using the question from this link as a reference How to repeatedly update the contents of a <div> by only using JavaScript?
but i have got few questions here
Can we do it without anonymous functions,using closures. I have tried but could not end up with any workable solution.
How can we make it run infinitely, with the following code it gets stopped once i reaches 10.
window.onload = function() {
var timing = document.getElementById("timer");
var i = 0;
var interval = setInterval(function() {
timing.innerHTML = i++;
if (i > 10) {
clearInterval(interval);
i = 0;
return;
}
}, 1000);
}
<div id="timer"></div>
I am confused about setIntervals and closures
can some one help me here
Thanks
You could do something like this with a closure. Just reset your i value so, you will always be within your given range.
window.onload = function() {
var updateContent = (function(idx) {
return function() {
if (idx === 10) {
idx = 0;
}
var timing = document.getElementById("timer");
timing.innerHTML = idx++;
}
})(0);
var interval = setInterval(updateContent, 1000);
}
<div id="timer"></div>
This one should be clearer.
function updateTimer() {
var timer = document.getElementById("timer");
var timerValue = parseInt(timer.getAttribute("data-timer-value")) + 1;
if (timerValue == 10) {
timerValue = 0;
}
timer.setAttribute("data-timer-value", timerValue);
timer.innerHTML = "the time is " + timerValue;
}
window.onload = function() {
setInterval(updateTimer, 1000);
}
<div id="timer" data-timer-value="0"></div>

JavaScript: Display array items after 3 seconds one a time

I have the code segment:
var i = 0;
(function loop() {
text_objects[i].displayText();
if (++i < text_objects.length) {
setTimeout(loop, 3000);
}
})();
Which is supposed to display the contents of an array one at a time, separated by 3 seconds. However, when I run the program, I only get the first item, and it sort of just freezes there, without updating and showing the rest of the items in the array.
What am I doing wrong?
As correctly mentioned by #nnnnnn,
loop() is a named function expression, and the reference loop should be in scope within the function
Also your code works fine.
var i = 0;
var test = function(value){
this.text = value;
}
test.prototype.displayText = function(){
document.write(this.text + "<br/>");
}
var text_objects = [];
for (var j = 0; j<10; j++){ text_objects.push(new test(j)); }
(function loop() {
text_objects[i].displayText();
if (++i < text_objects.length) {
setTimeout(loop, 3000);
}
})();
Alternate approach:
var i = 0;
function loop() {
document.write(i + "<br/>")
if (++i < 5) {
setTimeout(loop, 3000);
}
}
loop();
This works fine. Not sure if this is what you expect?
var i = 0;
Array.prototype.displayText = function(i) {
console.log(this[i]);
};
var text_objects = ['1', '2', '3'];
(function loop() {
text_objects.displayText(i);
if (++i < text_objects.length) {
setTimeout(loop, 3000);
}
})();
Following is my approach to the answer. Hope I helped!
var i = 0;
function loop() {
text_objects[i].displayText();
i = i + 1;
if (i < text_objects.length) {
setTimeout(loop, 3000);
};
};
setTimout(loop, 3000);

Delay time between each clicks on class

I have some loop like below..which clicks all buttons
for(var i = 1;i<document.querySelectorAll(".myclass").length;i++){
document.querySelectorAll(".myclass")[i].click();
console.log("hi");
};
but I want to add sleep function that delays each loop like sleep(2000); , Is there any function in javascript like that ?
I tried below code , but does not work
for(var i = 1;i<document.querySelectorAll(".myclass").length;i++){
setTimeout(function() {
document.querySelectorAll(".myclass")[i].click();
console.log("hi");
}, (3 * 1000));
};
var myVar = setInterval(myTimer, 2000);
var divIndex = 0;
function myTimer() {
if(divIndex < document.querySelectorAll(".myclass").length){
document.querySelectorAll(".myclass")[divIndex].click();
console.log(divIndex);
}else {
clearInterval(myVar);
}
divIndex++;
}
<div class='myclass'></div>
<div class='myclass'></div>
<div class='myclass'></div>
<div class='myclass'></div>
Create the new function as give and call that function inside your loop.
function sleep(milliseconds) {
var start = new Date().getTime();
while ((new Date().getTime() - start) < milliseconds) {
}
}
for (i = 0; i < 3; i++) {
console.log(i);
sleep(5000);
}

setTimeOut make alternate text for a jQuery ToolTip

while trying to learn some client side programming, i am implementing
a alternate tool-tip, on a span within a div , i am having a little problem to make the switch with java script for-loop
what is the proper way ?
html
<p id="TargetP">some initial text</p>
<br />
<input type="button" id="turnOn" value="hit it">
javascript
var texts = [];
texts.push("text one");
texts.push("text two");
$('#turnOn').on("click", function() {
myTimer();
});
function myTimer() {
var m = 0;
for (i = 0; i < 10; i++) {
m = (i % 2);
setTimeOut(function() {
alternateTT(m)
}, 1000);
}
}
function alternateTT(itemNo) {
var target = $('#TargetP');
$(target).text(texts[itemNo]);
}
This part of your code will not work as you expect:
for (i = 0; i < 10; i++) {
m = (i % 2);
setTimeOut(function() {
alternateTT(m)
}, 1000);
}
By the time your timeout function has been called, it will be in the context of the final loop. Thus m will be equal 10 % 2 in every call.
You you want to pass an explicit variable to the timeOut function you can do it like this:
var param = 1;
setTimeOut(function(param) {
alternateTT(param)
}, 1000, param);

Categories

Resources