.setTimeout function in javascript [duplicate] - javascript

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Function executing instantly, not waiting for setTimeout
(1 answer)
setTimeout not waiting specified time
(3 answers)
Closed 4 years ago.
could somebody help me to fully understand what is happening here please
let slideShowHandler = () => {
for(let i = 1; i <= mainElement.children.length; i++){
setTimeout(function(){
document.querySelector('#wrapper div:nth-of-type('+ i +')').style.display = "flex";
}, 3000 * i);
if(i == mainElement.children.length){
alert(i)
}
}
}
when I run the function, the alert comes up before all of the div's are displayed. I thought that it was waiting 3000ms * i and then updating i. but it looks like i goes to 4 and then the setTimeout function starts.
Any explanation to how exactly this is working would be fantastic

The function setTimeout is non-blocking and asynchronous. That is, it executes, and registers the callback function, and then happily continues to the next statement.

Related

How is setTimeout called in a for loop js? [duplicate]

This question already has answers here:
What is the JavaScript version of sleep()?
(91 answers)
Closed 2 years ago.
I am trying to write a for loop that has a delay between running each iteration. I thought Id go about it by using setTimeout() as follows.
Input:
for (let i=0;i<3;i++){
setTimeout(()=>{console.log("hi")},10000)
}
Output:
hi
hi
hi
What seems to be happening is that its waiting 10 seconds and then runs the entire for loop, rather than waiting 10 seconds to run each iteration of the for loop. After the first hi is shown to the console, the other 2 follow instantaneously. Why is this the case, rather than a delayed logging of hi and how can I go about doing this?
You don't call setTimeout() inside a for loop. You replace the for loop with setTimeout():
let loop = 0;
function loop () {
console.log("hi");
x++;
if (x<3) {
setTimeout(loop, 10000);
}
}
loop();
This is the traditional way of doing it. You can use a Promise with async/await in modern js to use the for loop again:
// First we need a promisified setTimeout:
function delay (ms) {
return new Promise((resolve,reject) => setTimeout(resolve,ms));
}
async function test () {
for (let i=0;i<3;i++){
await delay(10000);
console.log("hi");
}
}
test();
Javascript is asynchronous which means your timers start immediately rather than each timer blocking until done, and they all execute after roughly 10s plus a few ticks.
If you want you can try setInterval with a counter to clear it:
var counter = 0;
var interval = setInterval(function(){
console.log("hi");
counter+=1;
if (counter == 3) { clearInterval(interval); }
}, 10000);
You can probably work out an alternative using setTimeout as well.

can any one tell me what exactly setInterval() method in typescript? [duplicate]

This question already has an answer here:
setInterval and setTimeout in Typescript
(1 answer)
Closed 4 years ago.
Can any one please tell me how the setInterval() in angular is working .is java script functionality they implement in angular js ?
setInterval is a function that is exposed by the browser window as part of the global scope. Angularjs just makes use of it like any other javascript code could.
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval
setInterval is a function that continually invokes a callback after every X milliseconds, where X is provided to setInterval.
// setInterval usage
function callback(){
console.log("callback is called continuously");
}
var repeat = 3000;
setInterval(callback, repeat);
It will continue to run as long as your program is running.
Here's another example but with canceling setInterval
var num = 0;
var intervalId = setInterval(function() {
num++;
console.log("num:", num);
if(num === 3){
clearInterval(intervlId);
}
}, 1000);
// output
num: 1
num: 2
num: 3

Node.js setTimeout in forever loop [duplicate]

This question already has answers here:
Callback of an asynchronous function is never called
(1 answer)
setTimeout not working inside infinite loop
(5 answers)
Closed 5 years ago.
Can't explain nodejs behavior. I have code:
while (true) {
setTimeout(() => console.log(1), 0)
}
And this script just hanging...
How come? I've been thinking setTimeout is non-blocking and asynchronous, and nodejs use timers event loop phase for scheduling setTimeout callbacks... but it seems like event loop blocked...
Your while loop is infinite. It will just keep setting timeouts and never exiting the loop. Since JavaScript is single-threaded, the code for the timeouts won't run until the current code is finished, and since the while loop never finishes, the timeouts don't run.
If you want to spam the console with the number 1 using timeouts, which it looks like you are trying to do, you would have to set the next timeout in the current timeout's callback:
function timeoutFunc() {
console.log(1);
setTimeout(timeoutFunc, 0);
}
timeoutFunc();

What's the reason for the below code output in javascript [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 6 years ago.
for (var a=0; a<5; a++)
{
setTimeout(function(){
alert(a);
}, 0);
}
The above code in javascript is prompting me with the output of 5, 5 times infact my expectation was of the output something like 0,1,2,3,4 but rather it shows me the output of 5,5,5,5,5. Why is it so?
Besides that please explain me the concept of context and scope in javascript i always fail to understand it through many examples reading from the web.
Inside setTimeout(), your alert() is called asynchronously so it is very likely that for loop is already finish before alert() get executed.

How does setTimeout work? [duplicate]

This question already has answers here:
Calling functions with setTimeout()
(6 answers)
Closed 6 years ago.
-so i am obviously trying to get two functions to run automatically whilst on a timer using setTimeout. However i am not to sure how it works. All i can see when i search it up is it in a function. so how do i have it outside a function?
function ChangeImage() {
if(position < TrafficL.length) {
document.getElementById("myImage").src = TrafficL[position];
position++
}
}
function RestartPos() {
if (position==3)
document.getElementById("myImage").src = TrafficL["position"]
position=0
var setTimeout = (ChangeImage(),1500)
var setTimeout = (RestartPos(),6000)
You sould call setTimeout as a function:
setTimeout(ChangeImage,1500);
setTimeout(RestartPos,6000);
ChangeImage and RestartPos are like variables referencing a function. If you place parentheses behind them means, you are calling them immediately, but you want to call them after a given time.
You can store the value return by setTimeout() in a variable though, but it's only for cancelling the countdown later:
// nothing happens, because the timeout was cancelled in 1.5s
var t = setTimeout(ChangeImage,1500);
clearTimeout(t);

Categories

Resources