'setInterval' vs 'setTimeout' [duplicate] - javascript

This question already has answers here:
setTimeout or setInterval?
(20 answers)
Closed 9 years ago.
What is the main difference between
setInterval
and
setTimeout
in JavaScript?

setTimeout(expression, timeout); runs the code/function once after the timeout.
setInterval(expression, timeout); runs the code/function repeatedly, with the length of the timeout between each repeat.
Example:
var intervalID = setInterval(alert, 1000); // Will alert every second.
// clearInterval(intervalID); // Will clear the timer.
setTimeout(alert, 1000); // Will alert once, after a second.

setInterval fires again and again in intervals, while setTimeout only fires once.
See reference at MDN.

setTimeout():
It is a function that execute a JavaScript statement AFTER x interval.
setTimeout(function () {
something();
}, 1000); // Execute something() 1 second later.
setInterval():
It is a function that execute a JavaScript statement EVERY x interval.
setInterval(function () {
somethingElse();
}, 2000); // Execute somethingElse() every 2 seconds.
The interval unit is in millisecond for both functions.

setInterval()
setInterval is a time interval based code execution method that has the native ability to repeatedly run specified script when the interval is reached. It should not be nested into its callback function by the script author to make it loop, since it loops by default. It will keep firing at the interval unless you call clearInterval().
if you want to loop code for animations or clocks
Then use setInterval.
function doStuff() {
alert("run your code here when time interval is reached");
}
var myTimer = setInterval(doStuff, 5000);
setTimeout()
setTimeout is a time based code execution method that will execute script only one time when the interval is reached, and not repeat again unless you gear it to loop the script by nesting the setTimeout object inside of the function it calls to run. If geared to loop, it will keep firing at the interval unless you call clearTimeout().
function doStuff() {
alert("run your code here when time interval is reached");
}
var myTimer = setTimeout(doStuff, 5000);
if you want something to happen one time after some seconds
Then use setTimeout... because it only executes one time when the interval is reached.

setInterval repeats the call, setTimeout only runs it once.

Related

How is setInterval invoked here?

I have the following Javascript code attached to an HTML document with some CSS styling.
It is simply a box on the screen that changes the style background property colour according to those seen in the array. The id of "colour-changer" is used to access the HTML document and changes it each time the array is iterated.
The function declaration changeColour(); is used to make this happen by using colours.length to count its way through the array and then puts the array value into the HTML, which changes its background colour every 3 seconds.
Once it comes to the end of the array the counter is reset to 0, and it continues around again.
The setInterval method invokes the callback method changeColour() every 3 seconds to make this happen.
In order to stop the cycle, an onclick is event is added which invokes a clearInterval() method to print out "Timer stopped" inside the box. In order to do this the setInterval() method had to be stored in variable myTimer.
See the code below. It all works fine but this is not my real problem.
let colourChanger = document.getElementById ("colour-changer");
let colours = ["red","blue","green","pink"];
let counter = 0;
function changeColour(){
if (counter >= colours.length){
counter = 0;
}
colourChanger.style.background = colours[counter];
counter++;
}
let myTimer = setInterval(changeColour, 3000);
colourChanger.onclick = function (){
clearInterval(myTimer);
colourChanger.innerHTML = "Timer stopped";
}
What I cannot understand is the line let myTimer = setInterval(changeColour, 3000);
From my understanding if you store a function inside of a variable, it will NOT execute unless called separately. It will just sit there stored in the variable myTimer.
There is no setInterval(); call made outside of the variable anywhere.
MY QUESTION:
How then is this method invoked since it is simply stored inside of the variable myTimer?
No, your understanding is wrong.
It executes setInterval(changeColour, 3000); and stores this particular interval reference ID to myTimer to later be used in clearInterval(myTimer)
var myTimer = setInterval(() => console.log('ping'), 3000);
setTimeout(() => clearInterval(myTimer), 10000);
console.log('myTimer value: ', myTimer);
In order to do this the setInterval() method had to be stored in variable myTimer.
No, the return value of setInterval is stored in myTimer by that code. setInterval is called (it has (/*...*/) after it, which calls it).
From my understanding if you store a function inside of a variable, it will NOT execute unless called separately.
That's correct, but that's not what that line of code is doing. This code:
let myTimer = setInterval(changeColour, 3000);
calls setInterval and stores its return value in myTimer, exactly the way:
let x = example();
calls example and stores its return value in x.
It's the changeColour function that is only referenced, not called, by that code (there's no (/*...*/) after it). Doing that passes changeColour into setInterval, so that setInterval knows what function to call every three seconds or so.
So in that code, setInterval is called, and changeColour is just referenced (it's called later by the timer mechanism).
setInterval() function will return IntervalID, It will set execution interval for given milliseconds.
In your case once this line is executed it will start executing changeColour function every 3000ms / 3 seconds and return IntervalID.
Now this IntervalID is used to stop executing your function every 3 seconds in the future.
to stop executing you can use clearInterval(IntervalID).
if any doubts please comment.

setInterval continue running after return statement

a simple function has a setInterval function internally
why setInterval continue running even after function has complete return statement
function test(){
setInterval(()=>{
console.log(1)
},1000)
console.log('end')
return 0;
}
test() //output: end 1 1 1 1 1 1
setInterval(function, t ) is a webapi for calling a callback function after every t milliseconds. So that's the reason why it's running continuously.
setInterval evaluates your expression every Xms and needs to be clearead by clearInterval if you want it to stop.
What you are looking for is setTimeout which will run it only once.
If you’re goal is that the function will run one time after X sec/ms, you probably want to use setTimeout() function.
If you’re goal is to run a function every X sec/ms and to stop after X sec/ms, you can put a condition right before the setInterval() function.

Can't work setTimeout in componentDidMount

Try to build setTimeout() in React js. I setup this in componentnDidMount() but it works only once. Not working loop.
The code:
componentDidMount() {
setTimeout(console.log("hello"), 1000);
}
The warning show:
[Violation] 'setInterval' handler took 99ms
How can I repeat this function?
setTimeout(function, waitTime)
when you pass a function to the setTimeout method, the method waits for a specified amount of time waitTime, and it calls the function function.
But passing in console.log('hello') only simply logs out "hello", but does not return anything and thus does not actually pass a function or callable into the method.
Many ways to go around this:
setTimeout(function(){console.log("hello");},1000); //passes an actual function
setTimeout(()=>{console.log("hello");},1000); //lambda, passes an actual function
setTimeout(()=>console.log("hello"),1000); //same here
Also, if it was supposed to be repeated over intervals, then use setInterval (same arguments as setTimeout).
Use setInterval(). Here is a good explanation: setTimeout or setInterval?
setTimeout()
setTimeout() only execute one time when the time reached.
setInterval()
setInterval() is an interval based function and execute repeatedly when the interval is reached.
And examples for setTimeout() and setInterval(). Hope it helps.

How to execute a function before waiting with setInterval in JavaScript?

When using setInterval(f, time), is it possible that the function f is executed first before waiting for a time?
Not within the setInterval function itself. Just call it explicitly.
f();
setInterval(f, time);
Note : Even if you set an interval. It is not assured that the function will be triggered on time because javascript is single threaded and it will wait until the current executing function in the stack finishes.
The function passed inside setInterval wont fire the first time inside the setInteral. we have to invoke the function manually.
func();
setInterval(func, time);
If You want the function to be triggered before waiting x time, and then execute again after said time, and again and again, you have to explicitly call the function f before starting the interval like so:
var f = function () {
document.write('<p>Function executed</p>');
}
f();
setInterval(f, 3000);
Mind that the time is in milliseconds, so if you want the function to repeat every 1 seconds you should use the number 1000.
If you want the interval to be more precise consider putting it in a web worker, however support is not available in all browsers.

Does Javascript's setInterval block for function return?

I have a javascript function function a() that I want to be executed every 10 seconds.
I found that I can use the setInterval so that I can do something like: setInverval(a, 10000);
My question is the following:
Does this mean that
i) every 10 seconds the specified function is called (regardless if the previous execution is running/multithreaded way) OR
ii) that the function is called and when this function has finished execution then the next call of the function is scheduled after 10 seconds?
I am basically interested in option 2. If option 1 is what is happening by default then how could I achieve option 2?
Basically, setInterval runs according to option 1, except that if the function takes more than the interval time, it will not be fired again until it has finished and reached the next tick. For example, if you have an interval of 1 second and your function takes 1.5 seconds, it will run on the 2 second tick.
If you want the behaviour of option 2 (run X seconds after function completion), call setTimeout at the completion of your function instead:
setTimeout(function a() {
// your own code
setTimeout(a, 1000);
}, 1000);
How this works is that it first waits 1 second, then calls the function passed to setTimeout. At the end of the function, the function itself (a is the name of the function) is passed to setTimeout, which then waits another second to call the function again. This continues until JavaScript execution is halted or the timeout is removed by using clearTimeout.
Note that even if you use setInterval, the function will never be run concurrently, due to JavaScript's single-threaded nature.
setInterval(a, 10000) schedules a function to be called every 10 seconds, regardless of the time it took its previous invocations to complete. If you want to schedule the next call for 10 seconds after the completion of the last call, you should call setTimeout(a, 10000) within the a function itself, right before it returns, instead of using setInterval.

Categories

Resources