JavaScript: setTimeout not updating value inside loop - javascript

I'm aware of closures, IIFE.
I've read the other answers (they all point to using IIFE).
So why is this not working?
my image should gradually fade-in (in 2s)
it seems like it's only rendering once (with final value)
var imgFade = document.getElementById('img-fade');
for(i = 0; i < 100; i++){
(function(step) {
setTimeout(function() {
imgFade.style.opacity = (step/100);
}, 20);
})(i);
}
here's the code: https://jsfiddle.net/warkentien2/Lh10phuv/1/
EDIT: for future readers
consider all answers transitioning from i = 1; to 1 <= 100, i++ so it won't stop rendering at 99%

A quick but dirty way is multiplying the 20 by step. You create all the timeouts at once, so the ones that are supposed to be executed later have higher delay:
var imgFade = document.getElementById('img-fade');
for(i = 0; i < 100; i++){
(function(step) {
setTimeout(function() {
imgFade.style.opacity = (step/100);
}, step * 20);
})(i);
}

Heres another solution, applying the fade in one after another:
var fade = function(step){
imgFade.style.opacity = (step/100);
if(step < 100){
setTimeout(function(){ fade(++step); }, 20);
}
};
fade(0);

Related

CSS Clip-Path Animation with Javascript

I try to animate the Clip-Path Property with JavaScript.
Means: It "grows" with help of SetTimeout.
I tried this, but it doesn't work.
http://jsfiddle.net/071dm2h3/8/
var el = document.getElementById("image")
function grow(i) {
el.style.clipPath = "circle("+ i +"px at 190px 160px)";
}
var i;
for(i = 0; i < 100; i++) {
setTimeout(grow(i), 400);
}
What am I missing here? Shouldn't the setTimeout change the value of I in every loop, so that I can see the result immediately?
To get this to work, I rewrote your setTimeout to be around your loop to make the image grow.
setTimeout( function(){
for(i = 0; i < 100; i++) {
grow(i)
}
},400);
Here is the jsfiddle
No, setTimeout fires once, and only once. Additionally, the way you are using setTimeout will lead to unintended results. You are basically saying:
I want to call grow(i) 400 milliseconds from now 100 times.
That means that 400 milliseconds from now, grow(i) will be called 100 times simultaneously. You don't want that, you want to call `grow(i) 100 times, waiting 400 milliseconds between each iteration.
Instead, you should either use setInterval which will wait a duration between each call or have each setTimeout schedule the next timeout after a duration.
Consider:
This will wait 2 seconds and then print 1,2,3,4 all at the same time.
for (let i = 0; i < 5; i++) {
setTimeout(() => console.log(i), 2000);
}
This will print each iteration after a duration:
function iteration(i) {
console.log(i);
if (i > 3) return;
setTimeout(() => iteration(i + 1), 500);
}
iteration(0);
change you javascript to this
var el = document.getElementById("image")
function grow(i) {
console.log(i)
el.style.clipPath = "circle("+ i +"px at 190px 160px)";
}
var i;
for(i = 0; i < 100; i++) {
setTimeout( ((i) => () => grow(i))(i), i*10);
}
and kindly read this once
setTimeout in for-loop does not print consecutive values

How do I delay this code running in JavaScript?

I have written this code to change an image:
change = function(){
for (r=0; r<6; r++){
for (i = 0; i < 6 ; i++) {
setInterval(imgfile(number=i+1), 5000);
}
}
}
imgfile= function(number){
a = 'document.getElementById("imgdiv").src = "images/'+number+'.svg"';
eval(a);
}
The function change() is called when a button is clicked.
When I press the button the image changes straight to 6.svg, when I want it to go through the images 1, 2, 3, 4, 5, 6 and to repeat it 6 times. When I change setInterval to change.setInterval or imgfile.setInterval it doesn't work at all. How do I fix this?
change = function(i=0){
imgfile(i%6+1);//change image
if(i<36) setTimeout(change,5000,i+1);//next image in 5 seconds
}
imgfile= function(number){
document.getElementById("imgdiv").src = "images/"+number+".svg";//no need to use ev(i||a)l
}
Instead of loop/interval mess you can simply start a timeout that restarts itself after changing the image... This code will loop over 6 images with a delay of 5 seconds and that 6 times...
Something like this, perhaps?
var index, imgCount, loopCount, imgTag, countdown;
index = 0;
imgCount = 6;
loopCount = 6;
imgTag = document.getElementById('imgdiv');
countdown = function () {
if (index < imgCount * loopCount) {
imgTag.src = 'images/' + index % imgCount + '.svg';
index = index + 1;
setTimeout(countdown, 5000);
}
};
countdown();
Here we're avoiding the double loop and using modular math (index % imgCount) to get the right file number.
For another question I wrote a nice utility function that has quite a number of uses, but can also handle this scenario very easily. The main issue is that there is no time elapsing between the different delays being set. So you are setting 6 different actions to all happen within 5000ms, and all will occur at the same moment.
Here's my original answer
Here's the utility function for that answer, along with its application to your problem.
function doHeavyTask(params) {
var totalMillisAllotted = params.totalMillisAllotted;
var totalTasks = params.totalTasks;
var tasksPerTick = params.tasksPerTick;
var tasksCompleted = 0;
var totalTicks = Math.ceil(totalTasks / tasksPerTick);
var initialDelay = params.initialDelay;
var interval = null;
if (totalTicks === 0) return;
var doTick = function() {
var totalByEndOfTick = Math.min(tasksCompleted + tasksPerTick, totalTasks);
do {
params.task(tasksCompleted++);
} while(tasksCompleted < totalByEndOfTick);
if (tasksCompleted >= totalTasks) clearInterval(interval);
};
// Tick once immediately, and then as many times as needed using setInterval
if (!initialDelay) doTick();
if (tasksCompleted < totalTicks) interval = setInterval(doTick, totalMillisAllotted / totalTicks);
}
// Do 6 actions over the course of 5000 x 6 milliseconds
doHeavyTask({
totalMillisAllotted: 5000 * 6,
totalTasks: 6,
tasksPerTick: 1,
initialDelay: false, // Controls if the 1st tick should occur immediately
task: function(n) { console.log('Set image to "images/' + (n + 1) + '.svg"'); }
});
You want to do setTimeout().
setTimeout pauses for the millesecond value and then does the code. Where setInterval runs the code every whatever milleseconds.
Yeah, don't do change.setInterval or whatever, it is just setInterval.
An example for you would be this inside the for loop to replace the setInterval function.
setTimeout(imgfile(i+1), 5000);

Stop javascript increment at a certain value

I have coded this small script which increments a given value, in this case 200, by 1 every 3.2 seconds.
var i = 200;
function increment() {
i++;
document.getElementById('generated').innerHTML = Number(i).toLocaleString('en');
}
setInterval('increment()', 3200);
I'm trying to make the script stop increasing the value once it reaches a certain point (let's say 300 for example). I'm sure it's a simple fix but I can't think up of how to go about this.
You need to save the interval and then clear it:
var i = 200;
function increment() {
if (i >= 300) {
clearInterval(interval);
return;
}
i++;
document.getElementById('generated').innerHTML = Number(i).toLocaleString('en');
}
var interval = setInterval(increment, 3200);
Note that you can pass a function name instead of using the "interval()" string notation.
Here is a fiddle (I've sped up the time so that it doens't take forever to prove a point)
Hope it helps!
var i = 200;
function increment() {
if (i == 300) {
// stop when it hits 300
window.clearInterval(id);
return;
}
i++;
document.getElementById('generated').innerHTML = Number(i).toLocaleString('en');
}
var id = window.setInterval('increment()', 3200);
I think you could put it in IF statement as:
var i = 200;
function increment() {
if(i<300){
i++
}
}
increment();
You could use a for loop.
var i = 200;
var max = 300;
function increment() {
for (i < max; i++) {
document.getElementById('generated').innerHTML = Number(i).toLocaleString('en');
}
}
setInterval('increment()', 3200);
More info here: http://www.w3schools.com/js/js_loop_for.asp

How to create pause or delay in FOR loop?

I am working on a website, where I need to create a pause or delay.
So please tell me How to create pause or delay in for loop in javascript or jQuery
This is a test example
var s = document.getElementById("div1");
for (i = 0; i < 10; i++) {
s.innerHTML = s.innerHTML + i.toString();
//create a pause of 2 seconds.
}
You can't use a delay in the function, because then the change that you do to the element would not show up until you exit the function.
Use the setTimeout to run pieces of code at a later time:
var s = document.getElementById("div1");
for (i = 0; i < 10; i++) {
// create a closure to preserve the value of "i"
(function(i){
window.setTimeout(function(){
s.innerHTML = s.innerHTML + i.toString();
}, i * 2000);
}(i));
}
var wonderfulFunction = function(i) {
var s = document.getElementById("div1"); //you could pass this element as a parameter as well
i = i || 0;
if(i < 10) {
s.innerHTML = s.innerHTML + i.toString();
i++;
//create a pause of 2 seconds.
setTimeout(function() { wonderfulFunction(i) }, 2000);
}
}
//first call
wonderfulFunction(); //or wonderfulFunction(0);
You can't pause javascript code, the whole language is made to work with events, the solution I provided let's you execute the function with some delay, but the execution never stops.
I tried all one, but I think this code is better one, it is very simple code.
var s = document.getElementById("div1");
var i = 0;
setInterval(function () {s.innerHTML = s.innerHTML + i.toString(); i++;}, 2000);
if you want to create pause or delay in FOR loop,the only real method is
while (true) {
if( new Date()-startTime >= 2000) {
break;
}
}
the startTime is the time before you run the while
but this method will cause the browsers become very slow
It is impossible to directly pause a Javascript function within a for loop then later resume at that point.
This is how you should do it
var i = 0;
setTimeout(function() {
s.innerHTML = s.innerHTML + i.toString();
i++;
},2000);
The following code is an example of pseudo-multithreading that you can do in JS, it's roughly an example of how you can delay each iteration of a loop:
var counter = 0;
// A single iteration of your loop
// log the current value of counter as an example
// then wait before doing the next iteration
function printCounter() {
console.log(counter);
counter++;
if (counter < 10)
setTimeout(printCounter, 1000);
}
// Start the loop
printCounter();
While several of the other answers would work, I find the code to be less elegant. The Frame.js library was designed to solve this problem exactly. Using Frame you could do it like this:
var s = document.getElementById("div1");
for (i = 0; i < 10; i++) {
Frame(2000, function(callback){ // each iteration would pause by 2 secs
s.innerHTML = s.innerHTML + i.toString();
callback();
});
}
Frame.start();
In this case, it is nearly the same as the examples that use setTimeout, but Frame offers a lot of advantages, especially if the you are trying to do multiple or nested timeouts, or have a larger JS application that the timeouts need to work within.
I am executing a function where I need access to the outside object properties. So, the closure in Guffa solution doesn't work for me. I found a variation of nicosantangelo solution by simply wrapping the setTimeout in an if statement so it doesn't run forever.
var i = 0;
function test(){
rootObj.arrayOfObj[i].someFunction();
i++;
if( i < rootObj.arrayOfObj.length ){
setTimeout(test, 50 ); //50ms delay
}
}
test();
The way I found was to simply use setInterval() to loop instead. Here's my code example :
var i = 0;
var inte = setInterval(() => {
doSomething();
if (i == 9) clearInterval(inte);
i++;
}, 1000);
function doSomething() {
console.log(i);
};
This loops from 0 to 9 waiting 1 second in between each iteration.
Output :
0 1 2 3 4 5 6 7 8 9
It is not possible to pause a loop. However you can delay the execution of code fragments with the setTimeout() function. It would not make a lot of sense to pause the entire execution anyway.
I am using while loop and check the pause variable to check the user pause/resume the code.
var pause = false;
(async () => {
for (let index = 0; index < 1000; index++) {
while (pause) {
await new Promise((res) => setTimeout(res, 1000));
console.log("waiting");
}
await new Promise((res) => setTimeout(res, 1000));
console.log(index);
}
})();
const pausefunc = async () => {
pause = true;
};
const playfunc = () => {
pause = false;
};
<button onclick="playfunc()">Play</button>
<button onclick="pausefunc()">Pause</button>
I used a do...while loop to put a delay in my code for a modal dialog that was closing too quickly.
your stuff....
var tNow = Date.now();
var dateDiff = 0;
do {
dateDiff = Date.now() - tNow;
} while (dateDiff < 1000); //milliseconds - 2000 = 2 seconds
your stuff....

JavaScript setTimeout() Method on Animation

I have three yellow bars and each of them needs to come from left to right. For that, I have produced this code, but it only works on the last one. Can anyone correct this code; I need to work with pure JavaScript. I am not using any framework. Thanks.
window.onload = function(){
var yellowTitles = document.getElementById('magazine-brief').getElementsByTagName('h2');
for(i=0; i< yellowTitles.length; i++) {
var header = yellowTitles[i];
var timer = i*500;
var yellowBar = setTimeout(animeYellowBar,timer);
function animeYellowBar(){
header.style.left= "0";
}
}
}
Here's how I'd solve the problem:
var yellows = document.getElementById('magazine-brief').getElementsByTagName('h2');
// this will force the header number to be bound correctly
// also animates the div across the page by tracking the current position of x
function createMotion(num){
var currPos = 0;//current x position
var delta = 10;//move by this amount
setInterval(function(){
currPos += delta
yellows[num].style.left = currPos;
}, num * 500);
}
for (var i = 1; i < yellows.length; i++)
{
createMotion(i);
}
Note the function "createMotion" - added so the number "i" is correctly reference in the setInterval function.
Shouldn't you be incrementing your CSS left value instead of just setting it to 0? Why have a timeout at all if you're just going to set the value without gradually incrementing or decrementing?
If you do actually want to use a gradual animation, look at this tutorial : http://www.schillmania.com/content/projects/javascript-animation-1/
Very descriptive and possibly what you want.
By the time your timeout function runs, header refers to your last h2.
Try editing your timeout function to this:
function animeYellowBar(){
var thisheader=header;
thisheader.style.left= "0";
}
var yellows = document.getElementById('magazine-brief').getElementsByTagName('h2');
for (var i = 0; i < yellows.length; i++)
{
(function(idx, el){
window.setTimeout(function(){
var interval = window.setInterval(function(){
el.style.left = parseInt(el.style.left) + 10; // adjust this movement step
if (parseInt(el.style.left) >= 0)
{
el.style.left = 0;
window.clearInterval(interval);
}
}, 100); // adjust this number for animation speed
}, (idx++) * 500);
})(i, yellows[i]);
}

Categories

Resources