Can't work setTimeout in componentDidMount - javascript

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.

Related

Constructor function "creates" infinite loop in JS

I noticed some weird behavior in constructor functions. This code loops infinitely and I don't know why.
function thing(){
this.start=function (){console.log(this.msg)};
this.msg="Starting...";
setInterval(() => {this.start()},1000)
}
<button onclick="new thing()">Create a new thing!</button>
I've searched about this but I found nothing that explains this. Please someone help me and answer why this happens.
Thanks.
Are you sure you wanted to use setInterval not setTimeout? The former will callthis.start every 1 second, while the latter will be called once after 1 second,
Please take a look at the below links explaining both functions:
setInterval
https://developer.mozilla.org/pl/docs/Web/API/Window/setInterval
setTimeout
https://developer.mozilla.org/pl/docs/Web/API/Window/setTimeout
Correct snippet should be:
function thing(){
this.start=function (){console.log(this.msg)};
this.msg="Starting...";
setTimeout(this.start(), 1000)
}
<button onclick="new thing()">Create a new thing!</button>
It does so because setInterval() sets up an... You've guessed it! Interval, which continues to execute it's contents at the interval you've set (1000ms in this example).
setTimeout() will delay execution once at the set delay.
Yes setInterval will call after 1 sec so if you want to stop that you need to use clearInterval.
From the W3School documentation:
Definition and Usage
The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds).
The setInterval() method will continue calling the function until clearInterval() is called, or the window is closed.
The ID value returned by setInterval() is used as the parameter for the clearInterval() method.
Tip: 1000 ms = 1 second.
Tip: To execute a function only once, after a specified number of milliseconds, use the setTimeout() method.
So you may want to do:
function thing(){
this.start=function (){console.log(this.msg)};
this.msg="Starting...";
setTimeout(() => {this.start()}, 1000)
}
<button onclick="new thing()">Create a new thing!</button>
setInterval is actually supposed to start an interval (timed loop).
Also, you are executing the function rather than binding it :) Common mistake.
onclick="new thing()"
https://developer.mozilla.org/de/docs/Web/API/WindowTimers/setInterval
Your code can be done much simpler:
const start = () => setTimeout( () => console.log(200), 1000)
<button onclick="start">Start!</button>
In most cases, you will not need objects in JS. Functions as first-class objects are a very powerful feature of JS.

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);
}

Why does setTimeout works for endless recursive calls?

This is my recursive function :
function importTEI(index,data,header){
if (index == data.length){return}
var tei = new dhis2API.trackedEntityInstance();
tei.excelImportPopulator(header,data[index]);
tei.POST(requestCallback,requestCallback,index);
function requestCallback(response){
notificationCallback(response);
setTimeout(function(){
importTEI(response.importStat.index+1,importData,header);
},0);
}
}
The function importTEI is called within the function using setTimeout. When called without the setTimeout then after a few requests this error comes -
Uncaught RangeError: Maximum call stack size exceeded
But with setTimeout it runs forever....How come? What special thing is happening inside setTimeout? Is it no longer a recursive call?
Any tips are appreciated. Thnx.
It's no longer a recursive call. The setTimeout is a callback in the future and that call would be at the "top of the stack". The existing call to your function sets up this callback and then finishes its execution, resulting in zero recursion.
setTimeout function works only once. Look into your code. Inside the startTime function , you are calling the same function again in 0 ms. if you want it to repeat for sometime, use setInterval instead. This function returns a id using which you can stop it whenever you want.
refer this answer:
Why does the setTimeout function execute forever?

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.

How does jQuery accomplish its asynchronous animations?

...or more specifically, how are they able to create animations via javascript, which is synchronous, without holding up the next javascript statement.
It's just a curiosity. Are they using a chain of setTimeout()? If so, are they set early, each one with a slightly longer duration than the previous, and running parallel? Or are they being created through a recursive function call, therefore running in series?
Or is it something completely different?
There is an alternative to setTimeout() called setInterval() which will call the function you pass as argument at regular intervals. Calling setInterval will return a value which can be passed to clearInterval to stop the function from being called.
With jQuery 1.4.2 on lines 5534 - 5536:
if ( t() && jQuery.timers.push(t) && !timerId ) {
timerId = setInterval(jQuery.fx.tick, 13);
}
Notice the setInterval for jQuery's tick method that triggers a step in an animation.
Chained calls to setTimeout aren't really "recursive". If one setTimeout function, when called, sets up another timeout with itself as the handler, the original invocation will be long gone by the time the new timeout occurs.
Using setTimeout instead of setInterval is (to me) often more flexible because it lets the timed code adapt (and possibly cancel) itself. The general pattern is to set up a closure around the setTimout call so that the data needed by the timed process (the animation, if that's what you're doing) is available and isolated from the rest of the app. Then the timeout is launched on its initial run.
Inside the timeout handler, "arguments.callee" can be used for it to refer to itself and reset the timeout for subsequent "frames."

Categories

Resources