for(i=0;i<10;i++){
code
setTimeout
code
}
I want to prevent from the loop to proceed until timeout is finish ,any idea??
This repeats 10 times:
var j = 10;
setTimeout(someFunction, 1000);
function someFunction()
{
if (j > 0)
setTimeout(someFunction, 1000);
j = j - 1;
}
var i = 0;
nextMove( );
function nextMove( ) {
i++;
if( i != 10 ) setTimeout(nextMove,3000);
}
If you've got Function.prototype.bind() available:
function operation() {
if (!this) return;
// do something
setTimeout(operation.bind(--this), 1000);
}
setTimeout(operation.bind(10), 1000);
I believe there's no way to delay the execution of a block of code that follows an instruction that is being executed.
The only thing you can do is to wrap the code that need to be delayed around a function and use set time out just like the previous comments suggest.
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);
This question already has answers here:
How do I add a delay in a JavaScript loop?
(32 answers)
Closed 6 years ago.
I want to make a GreaseMonkey script. I want to have a setTimeout at the end of my while, but I don't know how to do that.
run();
function run(){
var klovas = document.getElementById("light").innerHTML;
var btn = document.getElementsByClassName("farm_icon farm_icon_a");
if(klovas < 6){
alert("Kevés egység van");
} else {
var i = 0;
while (i < btn.length){
if(typeof btn[i] != "undefined"){
btn[i].click();
}
i++;
setTimeout("run()", 3000);
}
}
}
With this code, the problem is that the setTimeout is not working and doesn't wait 3 seconds like it is supposed to.
I tried other ways, but nothing has worked.
EDIT
function run(){
var klovas = document.getElementById("light").innerHTML;
var btn = document.getElementsByClassName("farm_icon farm_icon_a");
if(klovas < 2){
alert("Kevés egység van");
} else {
var i = 0;
while (i < btn.length){
if(typeof btn[i] != "undefined"){
btn[i].click();
}
i++;
}
}
}
setInterval(run, 6000);
I tryed this. Its runing every 6 sec, but i get error in website, that i cand click more than 5 times in a sec. So waiting 6secound when i open the page, and after click, and i get error. Its not jet working. :(
If you wanted it to only trigger once:
function run(){
var data = [1,2,3];
var i = 0;
while (i < data.length) {
console.log(data[i]);
i++;
}
}
setTimeout(run, 3000);
The way you wrote it now, it would repeat every 3 seconds.
function run(){
var data = [1,2,3];
var i = 0;
while (i < data.length) {
console.log(data[i]);
i++;
}
setTimeout(run, 3000);
}
run();
But setInterval would accomplish the same results.
function run(){
var data = [1,2,3];
var i = 0;
while (i < data.length) {
console.log(data[i]);
i++;
}
}
setInterval(run, 3000);
EDIT
User wanted to see what would happen if you call setInterval from inside the callback function. Note that the number of intervals grows exponentially every 3 seconds.
setInterval causes the function to run every 3 seconds, while setTimeout causes the function to run once in 3 seconds.
var numberOfIntervals = 0;
function run(){
setInterval(run, 3000);
numberOfIntervals++;
console.log(numberOfIntervals);
}
run();
There are a few problems here.
Firstly, while setTimeout can accept a function as its first argument, you would want to pass the function as an argument, not execute the function, so you should replace "run()" with run.
Secondly, I'm not exactly sure why you're recursing -- why is setTimeout inside run()? Instead of putting it inside your run function, try putting it at the bottom, and deleting the run() call at the top. As far as I can tell, there's no reason that this code needs to recurse at alll.
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
can anyone please help me to figure out what this code javaScript code means
(function(){
for(var i=0;i<5;i++){
setTimeout(console.log(i),1000);
}
})();
You have run into very common closure issue. To fix this you can have for example self invoked function. Also you should pass function handler to setTimeout instead of invoking console.log:
for(var i=0;i<5;i++){
(function( i ) {
setTimeout( function( ) {
console.log(i);
},1000);
})( i );
}
If you want to print to console numbers from 0 to 4 in 1000ms interval you should use setInterval function:
var intervalHandler = null
, i = 0;
intervalHandler = setInterval( function() {
console.log( i );
if( i === 4 ) {
clearInterval( intervalHandler );
return;
}
i++;
}, 1000 );
Your code basically calls a function which is gonna log
0
1
2
3
4
A single time, why ? Because setTimeout is actually running setTimeout(undefined, 1000) 5 times, according to the return value of console.log, it will not evaluate a function, so the instruction is just lost.
Though from what I understand of what the code tries to say, to make the code work well, you could delegate the iteration control to a self calling function delayed with setSimeout
(function self(times, delay) {
self.config = self.config || {
times: times,
delay: delay,
iteration: 0
};
++self.config.iteration;
if (self.config.iteration <= self.config.times) {
console.log(self.config.iteration);
setTimeout(self, self.config.delay);
}
})(5, 1000);
for(var i=0;i<5;i++) //this code loop for five time before it break.
i.e, it will execute this function for five time setTimeout(console.log(i),1000);.
setTimeout() is a javascript function for delay and it going to delayed for 1s and it going to carry out action for console.log(i);.
I need one setInterval to start after another setInterval ends. Is there a way to do this with promises?
Ideally, I would like the code to look something like this:
for (i=0; i<5; i++){
setInterval(fun_1, 1000)
//wait until this is done
}
The setInterval calls the provided function after given interval of time until you clear its object. So you do not need a loop for this. You can use a counter to terminate it after counter reaches desired value.
Live Demo.
var myInter;
i = 1;
function fun_1()
{
// some code
if(i++==5)
clearInterval(myInter);
}
myInter = setInterval(fun_1, 1000);
Do you mean that you would like the second interval to begin the countdown after the previous interval is done? In that case, you would say
window.setTimeout(fun_1, 1000);
function fun_1
{
window.setTimeout(fun_2, 1000);
}
This starts the countdown for the second timeout after the first one has completed.
You should call the next interval after the first one completes
var cnt = 0;
function executeNextStep(){
fun_1();
if (cnt<5) {
window.setTimeout(executeNextStep,1000);
}
cnt++;
}
executeNextStep(); //execute this right away
//window.setTimeout(executeNextStep,1000); use this if you want it to be delayed
if you need to execute different functions:
function fun_1() {
console.log(1);
}
function fun_2() {
console.log(2);
}
function fun_3() {
console.log(3);
}
var fnc_stack = [fun_1, fun_2, fun_3];
var cnt = 0;
function executeNextStep(){
fnc_stack[cnt]();
cnt++;
if (cnt<fnc_stack.length) {
window.setTimeout(executeNextStep,1000);
}
}
executeNextStep();