delay with settimeout and for loop - javascript

I have this code from here:
How do I add a delay in a JavaScript loop?
I use it in console in IE, and after this code I call the function with myFunction() in console to run; This first code runs perfectly, it clicks on the second "something" tagnamed element 10 times and between the clicks are 3000 ms delay.
function myFunction() {
(function myLoop (i) {
setTimeout(function () {
document.getElementsByTagName("something")[1].click();
if (--i) myLoop(i); // decrement i and call myLoop again if i > 0
}, 3000)
})(10);
}
I would like to change the number "1" in this code with foor loop, so I want create a code which clicks on elements named "something".
I created this code, but is not working:
for (x=1;x<10;x++){
function myFunction() {
(function myLoop (i) {
setTimeout(function () {
document.getElementsByTagName("something")[1].click();
if (--i) myLoop(i); // decrement i and call myLoop again if i > 0
}, 3000)
})(10);
}
}

If you want to print each element at an interval you need to multiply the timing value with an integer, otherwise all of them will be logged at one time.
Also you may not need to create myFunction inside the loop
for (var x = 1; x < 5; x++) {
(function(i) {
setTimeout(function() {
console.log(i);
}, i * 1000)
}(x))
}

It usually easier to use setInterval rather the a loop with setTimeout. Everything is just simpler:
var count = 10
var intv = setInterval(function(){
if (count === 0 ) {
clearInterval(intv)
console.log("done")
return
}
// do something
console.log(count--)
}, 1000)
But you can recursively call setTimeout:
(function myLoop (i) {
setTimeout(function () {
console.log("loop: ", i)
if (--i) myLoop(i);
}, 1000)
})(10);
Putting the whole thing in a for loop AND calling it recursively is strange though, because the loop will run and make a bunch of individual timeouts that will all run independently, which I don't think is what you want.

function myFunction() {
(function myLoop (i) {
setTimeout(function () {
document.getElementsByTagName("div")[1].click();
if (--i) myLoop(i); // decrement i and call myLoop again if i > 0
}, 3000)
})(10);
}
for (x=1;x<10;x++){
myFunction();
}
<div>1</div>
Try like this. I used div instead of something

Related

How to run a delay function for 5 times in JavaScript?

I want to run a delay function for five seconds in JavaScript which will print "Hello" in the console after every second for five times.
Similar Python Code:
from time import delay
for I in range(5):
print("Hello")
delay(1)
The above code will print "Hello" five times with one second delay between each print.
Now I want to do similar kind of operation in JS.
Now in JS we have setTimeout function which will call a function after after a specified time. The following code will print "Hello" in the console after 1 second interval.
setTimeout(function(){
console.log("Hello");
}, 1000);
How can I run this code that will print 'Hello' in the console five times with an one second delay between each print?
NB: I tried to pass this function inside a for loop, but it did not work.
Try like this:
var count = 5;
printWithDelay();
function printWithDelay() {
setTimeout(function() {
console.log("Hello");
count--;
if (0 < count) {
printWithDelay();
};
}, 1000);
};
In JavaScript, 'setTimeout' runs after the code that follows it, so the next iteration of the loop needs to be called from within the callback function for this to work.
JavaScript, unlike PHP and Python, is asynchronous. The event loop is sensitive to anything that blocks it. However, there are ways to achieve what you want.
setInterval
With setInterval, you can build a wrapper it and use it.
function repeatFunction(func, delay, repeat) {
let counter = 0;
let interval = setInterval(() => {
if (repeat !== counter) {
func();
counter++;
} else {
clearInterval(interval)
}
}, delay);
}
repeatFunction(() => console.log(5), 1000, 4)
async/await syntax
The other option is using async/await with Promises (recommended)
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms))
}
(async() => {
for (let i = 0; i < 5; i++) {
console.log(i);
await sleep(1000);
}
console.log('done')
})();
Use setInterval, this should get your job done!
const test = setInterval(() => console.log("Hello"), 1000);
And then after 5seconds remove interval
setTimeout( () => clearInterval(test), 5000)
const test = setInterval(() => document.body.innerText += "Hello", 1000);
setTimeout( () => clearInterval(test), 5000);
NOTE: The first console.log() will happen after a second, if you want it immediately just put one console.log() outside the setInterval.

js, jquery - settimeout and for loop

I would like to do following instructions:
1. Fill input with id "ivoucher".
2. Click button with class "voucher-add-check".
3. Wait 5 seconds
And i would like to have it in for loop. I have following code, but it not working:
(function() {
'use strict';
for (var i = 1; i <= 3; i++) {
(function(a) {
jQuery('#ivoucher').val(i);
$('button[class*="voucher-add-check"]').click();
setTimeout(function() {
console.log(document.getElementById('ivouchermessage'));
}, i * 5000);
})(i);
}
})();
It seems you want the delay to happen before the next value is assigned. In that case you need an asynchronous loop. One way to do that is to call a function from within the setTimeout callback:
(function loop(i) {
if (i > 3) return; // all done
$('#ivoucher').val(i);
$('button[class*="voucher-add-check"]').click();
setTimeout(function() {
loop(i+1); // only now continue the "loop"
}, 5000);
})(1); // start value of i
Note that in your code:
you called the argument a, which you did not use.
all three assignments and clicks happened immediately (not subject to the timeout)

setTimeout function in JavaScript doesn't output number at correct time intervals

I'm not understanding why this function outputs 1-5 in successive order as intended, but at 1 second intervals rather than 1,2,3, etc. seconds. I'm unfamiliar with the setTimeout function and I understand that something is going on with the arguments to the function here that I'm not seeing.
var counter = function() {
for (var i = 1; i <= 5; i++) {
(function(x){
setTimeout(function timer() {
console.log(x);
}, (x * 1000));
})(i);
}
};
You can avoid the for loop by calling it recursively, just pass the start and stop index.
var counter = function (x, y) {
setTimeout(function timer() {
console.log(x);
if (x != y) counter((x + 1),y);
}, (x * 1000));
};
counter(1, 5);
Fiddle demo
Because you are immediately placing all your calls to setTimeout. So, during the same event, JS receives the instruction to call timer: after 1000ms, after 2000ms, after 3000ms, after 4000ms and after 5000ms. Which is exactly what it does, so timer is called every 1 second.
If you wish to progressively increase the interval, your loop should be rewritten as a recursive loop, in which the next call to setTimeout is performed by timer.
As #putvande said you are setting all 5 timeouts at the same time with different intervals.
var counter = function(){
for (var i=1; i<=5; i++) {
console.log('setting timer for ' + i);
(function(x){
setTimeout( function timer(){
console.log(x);
}, (x*1000) );
})(i);
}
};
counter();
An extra log statement show this. Your timers are firing at the right interval, 1st one at 1 second, 2nd one at 2 seconds, etc.

setTimeout() not working properly

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.

settimeout being ignore, function is called instantly

function ShowColoursScreen() {
setSquaresList()
$("#ModeOne").hide();
$("#ModeTwo").show();
setTimeout(function () {
$("#ModeOne").show();
$("#ModeTwo").hide();
setTimeout(function () {
ShowColoursScreen();
}, 1500);
}, 15000);
}
This is very very weird, Im wanting to rotated between two divs every 15 seconds (i dont want to use js intervals). However after the first fifteen seconds ShowColoursScreen(); runs without waiting the second 15 seconds (if that makes sense). Its like the timeout gets ignored, any ideas?
Your code is correct. However, the inner timeout just waits for 1.5 seconds as you forgot a zero. Simply replace the 1500 with 15000.
You can also simplify the call a bit - as you do not have any arguments there is no need for the anonymous function: setTimeout(ShowColoursScreen, 15000);
function ShowColoursScreen($elements) {
if(!$elements instanceof jQuery) {
$elements = $($elements);
}
var current = 0;
// What does this function do?
setSquaresList();
function showCurrent () {
var $currentElement = $($elements[current]);
$elements.not($currentElement).hide();
$currentElement.show();
(current++) % $elements.length;
setTimeout(showCurrent, 15000);
}
showCurrent();
return $elements;
}
ShowColoursScreen('#ModeOne, #ModeTwo')

Categories