How to execute a function before waiting with setInterval in JavaScript? - 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.

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 exactly works the setTimeout() JavaScript method?

I am not so into JavaScript and I have the following doubt related the setTimeout() method.
So into a test script I have:
function simpleMessage() {
alert("This is just an alert box");
}
// settimeout is in milliseconds:
setTimeout(simpleMessage, 5000);
So when I perform the page, after 5 second the simpleMessage() function is performed and it is shown the alert popup.
I understand that when I do:
setTimeout(simpleMessage, 5000);
it means that the simpleMessage() function have to be performed after 5 second after the timer settings but why it is used simpleMessage and not simpleMessage() for the function invocation?
simpleMessage is a reference to a function whereas simpleMessage() executes the function. setTimeout needs a function reference to call a later time.
To perhaps make things a little more obvious, you could have written your function declaration as
// define my function (but don't execute it)
var myFunction = function() {
alert('SOUND THE ALARMS!');
};
// start a timer that will execute the given function after the given
// period of time
setTimeout(myFunction, 5000);
See setTimeout documentation.
The first argument to setTimeout is the function to be executed. The identifier simpleMessage refers to the function you want setTimeout to execute, so that's what you supply as an argument to setTimeout.
If you did setTimeout(simpleMessage(), 5000);, you would execute simpleMessage immediately and then setTimeout would get the return value as its first argument. This is comparable to:
var value = simpleMessage();
setTimeout(value, 5000);
This doesn't make sense; it is the same as setTimeout(simpleMessage(), 5000);.
Consider also a higher-order function that returns a function:
function funcFacotry() {
return function() { alert("this is just an alert box."); }
}
var simpleMessage = funcFactory();
setTimeout(simpleMessage, 5000);
In this case, this actually does make sense, because the return value of funcFactory is actually a function itself.
setTimeout in javascript executes the function after a specific amount of time set as the second parameter, while if you use with setInterval it will execute in intervals, without to consider if the function is get executed or not (this will lead to chunkiness for example if you ar using for animation).
As a metter of second question: if you are using the function with parentheses, this is a method invocation, while using without parentheses is a reference to a specific method.
Because you need to pass a reference to setTimeout of the function you want to invoke after the 5s.
This:
setTimeout(simpleMessage(), 5000);
would execute the simpleMessage function at the same time you're calling the setTimeout function.

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