setInterval continue running after return statement - javascript

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.

Related

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.

a function that only calls input function f every 50 milliseconds

I am new to js.
I am trying to make a function that only calls input function f every 50 milliseconds.
wrote the code in the fiddle using setTimeout.
but isn't doing exactly what I wanted it to do
can you tell me how to fix it.
providing code below
https://jsfiddle.net/1pqznbgt/
function callSeconds(f){
setTimeout(function(){
alert("testing");
}, 500)
}
You are looking for setInterval instead of setTimeout (setTimeout will execute once, setInterval will execute at an interval)
The 500 in your sample means 500ms rather than 50ms
You will want to call f rather than your anonymous function, so:
What you are looking for is something like:
function callSeconds(f){
setInterval(f, 50);
}
The problem I see is that every time you call an alert() you are stopping execution of JavaScript and each browser can implement the alert differently . setTimeout() only executes once so if you call the function it will wait 500ms and issue an alert if you want a piece of code to operate continually you must use the setInterval() function but you still have the problem of how the browser chooses to handle the alert() function, normally an alert pauses execution of the current code, what effect that has on a timed execution function I do not know. I would try execution on something that does not pause or stop execution of the script. I also notice that in the code segment you have not invoked the parent function that would call the setTimeout function.
You can do one of 2 things here.
First, don't use setTimeout.
Instead use setInterval (f,50).
Or recursively call the function as so:
function foo (f){
f();
setTimeout (foo,50);
}

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.

'setInterval' vs 'setTimeout' [duplicate]

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.

Categories

Resources