So, I'm trying to use create a loop which does this:
setTimeout(function() {
console.log("Hey!");
setTimeout(function() {
console.log("Hey!");
setTimeout(function() {
console.log("Hey!");
}, 1000);
}, 1000);
}, 1000);
So, I tried it like this.
for (i = 0; 1 < 3; i++){
setTimeout(function() {
console.log("Hey!");
}, 1000);
}
How ever, it's not working.
Doing some research I've noticed this is because the timeOuts are getting added to each other with each loop. How can I work around this?
You have to recursively call the time outs, so write a function that takes an argument of the current number of attempts. Have it do an operation, and then call itself with the attempts argument += 1.
You should pass a number of attempts as a safeguard so you can tell the function not to call itself if the attempts number is > some limit, to avoid infinite loops.
Something like:
timedLog(attempts) {
console.log('Hey!');
if (attempts > 10) {
return;
} else {
setTimeout(function() { timedLog(attempts + 1); }, 1000);
}
}
It doesn't look like a for loop anymore, but it's the same principle.
If the output of each function is the same, and you want to print it in the same interval, then you could use setInterval.
function myInterval() {
return setInterval(function(){
console.log("Hey!");
}, 1000);
};
var id = myInterval();
It will repeat forever, so you would have to stop it, in this case, after 3000ms.
setTimeout(function(){
clearInterval(id);
}, 3000);
Just use a loop, increasing the timeout interval each time:
for (let i = 0; 1 < 3; i++){
setTimeout(function() {
console.log("Hey!");
}, i*1000);
}
(Note, that if your callback function depended on i, this won't work as expected if you use var instead of let in the for loop header. The reason is to do with closures - there are many questions about this on SO. But it works perfectly with let - and there are other simple enough fixes if for some reason you can't use let.)
Related
I have a for loop and I want to print its i'th value after a delay but with setTimeout() function, it waits for specified time but then every value of i prints without any delay. Is this because setTimeout() is an Async function and by the time it completes its first countdown, the time for all other values is also over.
for(let i=0;i<10;i++){
setTimeout(()=>{
console.log(i);
},10);
}
OUTPUT:
(10ms Gap) 1-2-3-4-5
OUTPUT REQUIRED: 1 - 10ms Gap - 2 -10ms Gap--... So on. Kindly provide the reason for solution.
You are repeatedly calling setTimeout() in your loop, if you just want to delay your loop, you could try something like this.
loopWithDelay();
async function loopWithDelay() {
for(let i = 0; i < 10; i++){
console.log(i)
await delay(100);
}
}
var timer;
function delay(ms) {
return new Promise((x) => {
timer = setTimeout(x, ms);
});
}
You are correct that the setTimeout is asynchronous, therefore every console.log(i) is set to run at basically the same time. I find it easier to use setInterval in your scenario:
let i = 0;
let myInterval = setInterval(() => {
console.log(i);
i++;
if (i === 10) {
clearInterval(myInterval);
}
}, 10);
You can modify the timer in the loop for every item.
for(let i=0;i<10;i++){
setTimeout(()=>{
console.log(i);
},10*(i+1));
}
This ensures proper gap between every item.
I hope it helps.
Yes, setTimeout() is an async function and all the countdowns start at almost the exact time because there is no waiting time between succesive setTimeout() calls.
What you can do in order to get the expected behaviour is put the for in a function and call that function back from setTimeout() when the countdown runs out:
function f(i) {
if(i < 10) {
setTimeout(()=> {
console.log(i);
f(i+1);
}, 10);
}
}
f(0);
I have a list of events with timestamp.
What I want is to display the events based on the timestamp:
To add a delay:
delay = timestamp(t+1) - timstamp(t)
I know this doesn't work well with setTimeout, but there is an workaround, if the timeout is constant, in my case is not.
Is it possible to make the next setTimeout() wait for the previous one? To be specific, if the first setTimeout() has a 5 second delay and the second one has 3 seconds, the second one will appear first. I want them to be in the same order but execute one after the other.
This example works for a constant delay, but I want to calculate the delay based on the information I take iterating the list.
for (i = 1; i <= 5; ++i) {
setDelay(i);
}
function setDelay(i) {
setTimeout(function(){
console.log(i);
}, 1000);
}
You can use IIFE (Immediately Invoked Function Expression) and function recursion instead. Like this:
let i = 0;
(function repeat(){
if (++i > 5) return;
setTimeout(function(){
console.log("Iteration: " + i);
repeat();
}, 5000);
})();
Live fiddle here.
When using the latest Typescript or ES code, we can use aync/await for this.
let timestampDiffs = [3, 2, 4];
(async () => {
for (let item of timestampDiffs) {
await timeout(item * 1000);
console.log('waited: ' + item);
}
})();
function timeout(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
We need to wrap the for loop in an async immediately invoked function because to support await.
We also do need a timeout function that returns a promise once the timeout is complete.
After that, we wait for the timeout to complete before continuing with the loop.
Don't call it within a loop, as it won't wait for the setTimeout to complete.
You can instead pass a list of times that you want to wait, and iterate them recursively:
let waits = [5000, 3000, 1000];
function setDelay(times) {
if (times.length > 0) {
// Remove the first time from the array
let wait = times.shift();
console.log("Waiting", wait);
// Wait for the given amount of time
setTimeout(() => {
console.log("Waited ", wait);
// Call the setDelay function again with the remaining times
setDelay(times);
}, wait);
}
}
setDelay(waits);
You can set time out period using i value dynamically. Like
for (i = 1; i <= 5; ++i) {
setDelay(i);
}
function setDelay(i) {
setTimeout(function(){
console.log(i);
}, i*1000);
}
You can think of something like that:
setDelay(1,5);
function setDelay(i, max) {
setTimeout(function(){
console.log(i);
if(i < max){
i++;
setDelay(i, max);
}
}, 1000);
}
The idea is to set the next setTimeout(.. in a timeout.
Of course you can modify it to have different long timeouts as well.
Hope i can help :)
Here is my code
(function() {
(function DeleteREG(i) {
setTimeout(function() {
if (i > 0) {
setTimeout(function stop_() {
alert(i);
}, 2000);
setTimeout(function() {
i--;
DeleteREG(i);
}, 800);
}
}, 4000);
})(5);
})();
According to the code it should alert at i=5,4,3,2,1.But it alerts at i=4,3,2,1,0.Can anyone please explain me why it is not working?what should be rectified to the code to work properly?Same thing happens for the following code also
(function() {
(function DeleteREG(i) {
setTimeout(function() {
if (i > 0) {
setTimeout(function stop_() {
alert(i);
}, 2000);
i--;
DeleteREG(i);
}
}, 4000);
})(5);
})();
And please explain me the solution in written format.How to get rid of this problem?
When you call setTimeout, your code doesn't stop.
Those two functions defined here :
setTimeout(function stop_() {
alert(i);
}, 2000);
setTimeout(function() {
i--;
DeleteREG(i);
}, 800);
They're called 2000 and 800 ms after the same moment. That's why i-- comes before the alert of the first callback.
A "solution" might be to chain the first of those callback in the second one :
(function() {
(function DeleteREG(i) {
setTimeout(function() {
if (i > 0) {
setTimeout(function stop_() {
console.log(i);
setTimeout(function() {
i--;
DeleteREG(i);
}, 80);
}, 200);
}
}, 400);
})(5);
})();
the functions that are passed to the 2 setTimeouts are created in the same execution scope ( an execution scope is created when a function is executed ) that's why they share the same i variable. The second callback will be fired before the first, therefore altering the i variable.
setTimeout pushes a message into a message queue after x milliseconds have passed, x being the time you passed as the second parameter. Anyway, the callback passed to setTimeout will always run after the current stack has been finished. This happens even if you pass 0 milliseconds ( read more details here).
UPDATE: I'm not sure what are you trying to achieve, but if you want to count from 5 to 1, this would do:
var delay = 1000;
function doStuff (i) {
if ( i > 0 ) {
alert(i);
i -= 1;
setTimeout(function () {
doStuff(i);
}, delay);
}
}
doStuff(5);
Check Out if you're not using throttling options on chrome. It can simulate a slow device, changing timing for intervals.
What I want is an infinite loop that alerts 1, 2, 3, 1, 2, 3, ... with an interval of 2000 milliseconds. But it's not working. The console's not showing any error though. What's the problem here?
for (i = 1; i <= 3; i++) {
setInterval(function() {
alert(i);
}, 2000);
if (i == 3) {
i = 0;
}
}
This will do:
var i = 0;
setInterval(function () {
i += 1;
if (i == 4) {
i = 1;
}
alert(i);
}, 2000);
I've checked it chrome too.
It outputs 1,2,3,1,2,3... as you have requested.
you can not setInterval() inside a for loop because it will create multiple timer instance.
The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds).
The setInterval() method will continue calling the function until clearInterval() is called, or the window is closed.
The ID value returned by setInterval() is used as the parameter for the clearInterval() method.
Tip: To execute a function only once, after a specified number of milliseconds, use the setTimeout() method.
var i = 0
function test() {
i = i % 3;
++i;
alert(i);
};
setInterval('test()', 2000);
You would not need a loop for this, an interval already goes on infinitley. Try this instead:
var i = 1;
setInterval(function() {
alert(i);
i++;
if(i > 3) {
i = 1;
}
}, 2000);
The reason why this is not working is because you enter the infinite loop in a blocking state, meaning that the interval is never entered as the browser is busy looping. Imagine the browser can only do one thing at a time, as in a single thread, so the loop is it, and cannot do anything else until it's done, and in your case it never is, therefore the interval is waiting for it's turn, which it never gets.
You could make it none blocking like this:
function recursion () {
for (var i = 1; i < 4; i++) {
var num = i;
setInterval(function() {
console.log(String(this));
}.bind(num), 2000);
}
recursion ();
}
recursion ();
my best suggestion is . use event monogramming righterthen loop ,
first make a function then after completing of setInterval call to next function and so on.. that's how u can solve this p
There is a function which sets an interval using setInterval(), but even after calling clearInterval(), I can see in the console that the else condition is still running. How can I clear that interval properly?
function increase(old, step, neu) {
var i = 0;
var delay2;
function countUp() {
if (i < 5) {
old += step;
// console.log("increase")
$("#total-price-value").text(old + " dollors");
$("#total-price-value").digits();
i++;
delay2 = setInterval(countUp, 80);
} else {
clearInterval(delay2);
console.log(delay2);
}
}
countUp();
}
It looks like you're a little confused about the difference between timeouts and intervals. Timeouts fire only once; intervals fire many times. If you're using an interval, you probably only want to set it once (you're setting it every time). If you're using a timeout, you probably want to set it every time (like you're doing).
In order to fix the problem, you'll either want to switch to timeouts (probably the easiest; just a search/replace) or only set the interval once.
For example, here is how one might use setTimeout to count up to five:
var count = 0;
function timeoutFired() {
count++;
if(count < 5) {
setTimeout(timeoutFired, 1000);
}
}
setTimeout(timeoutFired, 1000);
Using timeouts, we don't need to clear to stop it from counting; simply not setting a timeout will prevent it from running again.
Here is how one might use setInterval:
var count = 0;
function intervalFired() {
count++;
if(count >= 5) {
clearInterval(interval);
}
}
var interval = setInterval(intervalFired, 1000);
If you want some code running periodically using intervals to stop, you must call clearInterval. Note that we only call setInterval once, versus setTimeout every time we didn't want it to continue.
Apparently, you have mistaken setInterval for setTimeout. setInterval runs the enclosed function every n milliseconds while setTimeout executes only once after n milliseconds.
I suppose you wanted to "tick until 5" so here's a sample:
function increase(old, step, neu) {
var i = 0;
interval = setInterval(function() {
if (i < 5) {
//do something at this "tick"
console.log(i);
i++;
} else {
//else, stop
clearInterval(interval);
}
},80);
}
increase();