setInterval doesn't seem to work in loops well - javascript

I'm having problem with intervals in loops.
here is my code:
for(i=0;i<=10;i++){
(function(i){
set = setInterval(function(){
alert("hello, world.") // for example.
},1000);
})(i);
};
I expect this to happen any 1000 miliseconds, but when it starts it waits for 1000 miliseconds and then execute as usual loop;
i can handle it like this:
var i = 0;
set = setInterval(function(){
alert("hello, world.");
i++;
if(i == 10){
clearInterval(set);
};
},1000);
but i don't really want to plan my code in this way.
i gotta use loops.
thanks in advance.
why this doesn't work:
<div id="lbl"></div><br>
<script>
function fun(){
var text = "in the name of god";
var lbl = document.getElementById("lbl");
var arr = new Array("a","b","c","d","e","f","g","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"," ",0,1,2,3,4,5,6,7,8,9);
for(x in text){
var spn = document.createElement("span");
lbl.appendChild(spn);
for(i=0;i<=arr.indexOf(text[x]);i++){
(function(i){
setTimeout(function(){
spn.innerHTML = arr[i];
},i*200);
})(i);
};
};
};
fun();
</script>

You need to invert this--let the timer drive the loop, not the loop drive the timer.
Based on your example:
<label id="lbl"></label><br>
<script>
function ok(a){
var arr = new Array("a","b","c","d","e","f","g","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",0,1,2,3,4,5,6,7,8,9);
var lbl = document.getElementById("lbl");
var i = 0, iMax = arr.indexOf(a);
function next()
{
lbl.innerHTML = arr[i];
if (++i <= iMax) {
setTimeout(next,i * 200);
}
}
setTimeout(next,0);
}
ok("z");
</script>

Related

i want to make a counter function dynamic in javascript

i have called a counter function in loop. there are 4 items per page.
i have passed $i in loop and written 4 functions
but if i changed pagination limit to 5 or 10 ,it is not a good solution
anybody can help me to solve it?
here is my div in foreach loop where l called function
<div class="tick"
data-value="'.$start.'"
data-did-init="handleTickInit'.$i.'">
<div data-layout="horizontal center"
data-repeat="true"
">
<div data-view="swap"
></div>
</div>
handleTickInit'.$i is function
function handleTickInit2(tick) {
var value = tick.value;
var target = 0;
var timer = Tick.helper.interval(function() {
// have we reached the donation target yet?
if (value>=target) {
// no, keep going
var realprice=$("#realprice-2").val();
var startdate=$("#startdate-2").val();
var currenttime = Math.round((new Date()).getTime()/1000);
var stepsec=$("#stepsec-2").val();
// alert(stepsec);
var diffsec=currenttime-startdate;
var loss=diffsec*stepsec;
var start=realprice-loss;
tick.value = start.toFixed(4);
$("#saveval-2").val(start);
// value= tick.value ;
}
else {
// yes, stop the timer
timer.stop();
}
}, 1000);
}
please give some solution to make it dynamic
Try this
var handleTickInit = {};
var num = 5;
var handleFunc = function() {
return function (tick) {
var value = tick.value;
var target = 0;
var timer = Tick.helper.interval(function() {
// have we reached the donation target yet?
if (value>=target) {
// no, keep going
var realprice=$("#realprice-2").val();
var startdate=$("#startdate-2").val();
var currenttime = Math.round((new Date()).getTime()/1000);
var stepsec=$("#stepsec-2").val();
// alert(stepsec);
var diffsec=currenttime-startdate;
var loss=diffsec*stepsec;
var start=realprice-loss;
tick.value = start.toFixed(4);
$("#saveval-2").val(start);
// value= tick.value ;
}
else {
// yes, stop the timer
timer.stop();
}
}, 1000);
}
}
for(var i = 0; i< num; i++){
handleTickInit[i] = handleFunc();
}
console.log(handleTickInit);
All your handle tick functions are in handleTickInit;

For loop is looping too much

I am looping through a for loop to perform a simple calculation. The results of each iteration are stored into an array. The array has the correct number of elements but the output has exponentially too many elements.
HTML:
<script type="text/javascript" src="Fibonacci.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
(function($) {
$.fn.writeText = function(content) {
var contentArray = content,
current = 0,
elem = this;
setInterval(function() {
if(current < contentArray.length) {
elem.text(elem.text() + contentArray[current++]);
}
}, 1000);
};
})(jQuery);
</script>
</head>
<body>
<script>
document.write(getArray());
$(document).ready(function($){
var contentArray = getArray();
$('#calculations').writeText(contentArray);
});
</script>
<h3>Fibonacci Sequence:</h3>
<p id='calculations'></p>
External JS:
var result;
var x = 0;
var y = 1;
var resultArray = [x,y];
function FibonacciCalculation(){
for(var i = 2; i < 5; i++){
result = x + y;
x = y;
y = result;
resultArray.push(result);
}
}
function getArray(){
FibonacciCalculation();
return resultArray;
}
window.onload = function(){
FibonacciCalculation();
};
You need to reset your resultArray every time you run FibonacciCalculation function:
function FibonacciCalculation() {
resultArray = [x, y]
// ...
You called getArray two times the <script> part of the html so resultArray is called several time (2 and 4th line).
<script>
document.write(getArray());
$(document).ready(function($){
var contentArray = getArray();
$('#calculations').writeText(contentArray);
});
</script>
Also you should correct the < to > in your if condition because it seems that it will always be true.
if(current < contentArray.length) {
elem.text(elem.text() + contentArray[current++]);
}

How to display innerHTML values one by one javascript

Trying to display the values of my inner HTML, from 10 to 1, but am able to show only the value 1.
the values should display, one by one..
For example if 10 get displays, it should hide and then 9 should display,
it just like a timer.
How to fix this, this is what I have tried.
HTML:
<div id='test'></div>
JS:
var a = 10;
var b=1;
var tar = document.getElementById('test');
for(var a=10;a>=b;a--){
tar.innerHTML = a;
if(a==b){
tar.innerHTML = a;
//tar.style.display='none';
window.location.href = "http://www.google.co.in";
}
}
fiddle demo
The problem you have is that JavaScript can execute incredibly fast, so it is counting from 10 to 1 faster than you can see. You need to slow it down a little with a timer...
In this example, there is a one second delay between each number.
var a = 10;
var b = 1;
var tar = document.getElementById('test');
var timer;
function countDown() {
tar.innerHTML = a;
if(a === b) {
tar.innerHTML = a;
//tar.style.display = 'none';
window.location.href = "http://www.google.co.in";
} else {
a--;
timer = window.setTimeout(countDown, 1000);
}
}
countDown();
<html>
<head>
<script>
var myVar = setInterval(function(){myTimer()}, 1000);
var i=10;
function myTimer() {
i--;
if(i==1)
clearInterval(myVar);
document.getElementById("test").innerHTML = i;
}
</script>
</head>
<body>
<div id="test"></div>
</body>
</html>
You can simply do:
var counter = 10; // number of iterations
var tar = document.getElementById('test');
var interval = setInterval(function(){
if (counter === 0) clearInterval(interval); // skip if reached end
tar.innerHTML = counter; // update html
counter--; // update counter value
}, 1000) // 1000 = 1 second
See Fiddle
http://jsfiddle.net/0sbu5f8c/13/
var a = 10;
var b = 1;
var tar = document.getElementById('test');
var timer = setInterval(function () {
tar.innerHTML = a;
if(a === b) {
window.clearInterval(timer);
//window.location.href = "http://www.google.co.in";
}
a -= 1;
}, 500);

javascript clear timeouts in loop

The code below appends numbers in sequence from 1 to 10 when the start button is clicked. I'd like to use clearTimeout to cancel the operation when the stop button is clicked.
It seems to me that a dynamic variable must be created (where x is currently assigned the doSetTimeout function), but I have not yet found a way to do so. Any suggestions?
Thanks!
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function doSetTimeout(func, func_param, time) {
setTimeout(function(){func(func_param);}, time);
}
function createNode(base) {
var node = document.createElement("p");
var writeI = base + "";
var textnode = document.createTextNode(writeI);
node.appendChild(textnode);
document.body.appendChild(node);
}
$(document).ready(function() {
$("#start").click(function() {
for (var i = 1; i <= 10; i++) {
var time = i*1000;
var x = doSetTimeout(createNode, i, time);
}
});
});
</script>
</head>
<body>
<button id="start">Start</button>
<button id="stop">Stop</button>
</body>
Get the return value of setTimeout, keep it in a list, and clear it when you click stop.
function doSetTimeout(func, func_param, time) {
return setTimeout(function(){func(func_param);}, time);
}
$(document).ready(function() {
var timeouts = [];
$("#start").click(function() {
for (var i = 1; i <= 10; i++) {
var time = i*1000;
timeouts.push(doSetTimeout(createNode, i, time));
}
});
$("#stop").click(function () {
for (var i = 0; i <= timeouts.length; i += 1) {
clearTimeout(timeouts[i]);
}
});
});
This might also clear timeouts that have already finished, but I doubt that's really very important.

add div tags after specific amount of time repeatedly in javascript/jquery

I need to add append 10 div tags to another one but I need to wait random time before appending each one, something like this:
function start()
{
for (var i= 0; i< 10; i++)
{
var time = generateRandomWaitingTime();
sleep(time);
$('#div1').append('<div> div num' + i + '</div>');
}
}
I tried implementing my own sleep(time); function like here but it didn't work with me as it hangs any page event till the wait(time) finishes
setTimout() Seems to be exactly what you're looking for.
You should make use of setTimeout and a closure:
//closure
var addElement = function(i){
return function(){
$('#div1').append('<div> div num' + i + '</div>');
};
};
function start() {
for (var i = 0; i < 10; i++) {
var time = generateRandomWaitingTime();
setTimeout(addElement(i), time);
}
}
Living demo: http://jsfiddle.net/JaR34/
Update:
Living demo: http://jsfiddle.net/JaR34/1/
try this:
var elements = [1000,2000,3000,4000,5000,6000,7000];
function generateRandomWaitingTime(){
//will give you random index
var index = Math.floor((Math.random()*elements.length));
return (elements[index]);
}
function appendDiv(i){
var time = generateRandomWaitingTime();
setTimeout(function () {
$('#div1').append('<div> div num' + i + '</div>');
}, time);
}
for (var i = 0; i < 10; i++) {
appendDiv(i)
}
working fiddle here: http://jsfiddle.net/6neFA/1/

Categories

Resources