Settimeout just after a function - javascript

I'm trying to make a removeClass function work right after another function ends, so I have this script to call a fittocontainer:
function fittocontainer(){
$('.fittocontainer').fittocontainer()
}
And I want that after the function 'fittocontainer' ends, apply this function:
setTimeout ( function(){
$('#footer').removeClass("active");
})
How can I integrate the setTimeout function with the 'fittocontainer()' to work after it has just ended?

Is fittocontainer a function that you made? If so, and it is asynchronous, you will have to add a callback like:
function fittocontainer (cb) {
//do some stuff
cb();
}
Then you can call it passing a function or even an anonymous function like:
fittocontainer(function () {
// do stuff afterwards
});
If this function is updating the DOM it is most likely asynchronous. Using a timeout to try and execute code after an async method is very dangerous and should never be done.
If it is synchronous, you can simply call a function on the next line and know that it will execute after fittocontainer is complete.
Also remember that you need a timeout on the setTimeout like:
setTimeout(function(){
$('#footer').removeClass("active");
}, 1000);
that is a timeout of 1 second

setTimeout() is about time (minutes, seconds), if you only want to execute that function at the end, you could just call it, or you could use a callback function:
function fittocontainer(callback){
$('.fittocontainer').fittocontainer();
callback();
}
and then call fittocontainer:
fittocontainer(function(){
$('#footer').removeClass("active");
});

Related

Javascript callbacks not working as expected .? Want to know what is causing an error as such .? [duplicate]

How come I can say:
var myFunction = function() {
setTimeout(myFunction, 1000);
}
myFunction();
Why does the function call in the setTimeout not require parentheses, but the last line does?
Nutshell
myFunction references the function
myFunction() calls the function
More Words
setTimeout expects a function reference* as an argument.
There are circumstances where setTimeout(myFunction(), 1000) might make sense, like if myFunction() returns a function, e.g.
function myFunction() {
return function() {
alert("ohai")
}
}
// Or
const myFunction = () => () => alert("ohai")
So:
setTimeout(myFunction(), 1000);
setTimeout gets the return value of myFunction
myFunction returns a function (that calls alert)
meaning there will be an alert every second.
See also Why function statement requires a name?
* Or a string to be evaluated, but a reference is preferred.
myFunction is a function
myFunction() calls the function and yields whatever value the function returns.
The purpose of setTimeout is running code after some time elapses. You need to pass just the function to it (so setTimeout can itself call the function when appropriate) because if you called the function (with the parenthesis) before passing it to setTimeout it would execute now instead of after 1 second.
When you use the parenthesis, it's saying 'call this function now'. So if you say setTimeout(myFunction(),1000);, it will use the return value of the function as the callback for the timeout. If the return value for the function is not itself a function, you'll get an error because it will try to execute something that isn't executable after the timeout (a string, a number, undefined, etc).
In line 2, the function myFunction is not called, but passed as an argument to the setTimeout function, whereas in line 4 myFunction is called; to call a function, you always have to use parentheses, even if there are no arguments.
I think this example would make it clearer if i may,
function callback() {
console.log('this function runs on page loads.');
}
setTimeout(callback(), 2000);
Here callback() function will run immediately after page loads and won't wait 2 seconds.
function callback() {
console.log('this function runs after page loads.');
}
setTimeout(callback, 2000);
Here callback() function will run after 2 seconds.

async operation triggered inside setTimeout(), not working when application unmounts from dom [duplicate]

How come I can say:
var myFunction = function() {
setTimeout(myFunction, 1000);
}
myFunction();
Why does the function call in the setTimeout not require parentheses, but the last line does?
Nutshell
myFunction references the function
myFunction() calls the function
More Words
setTimeout expects a function reference* as an argument.
There are circumstances where setTimeout(myFunction(), 1000) might make sense, like if myFunction() returns a function, e.g.
function myFunction() {
return function() {
alert("ohai")
}
}
// Or
const myFunction = () => () => alert("ohai")
So:
setTimeout(myFunction(), 1000);
setTimeout gets the return value of myFunction
myFunction returns a function (that calls alert)
meaning there will be an alert every second.
See also Why function statement requires a name?
* Or a string to be evaluated, but a reference is preferred.
myFunction is a function
myFunction() calls the function and yields whatever value the function returns.
The purpose of setTimeout is running code after some time elapses. You need to pass just the function to it (so setTimeout can itself call the function when appropriate) because if you called the function (with the parenthesis) before passing it to setTimeout it would execute now instead of after 1 second.
When you use the parenthesis, it's saying 'call this function now'. So if you say setTimeout(myFunction(),1000);, it will use the return value of the function as the callback for the timeout. If the return value for the function is not itself a function, you'll get an error because it will try to execute something that isn't executable after the timeout (a string, a number, undefined, etc).
In line 2, the function myFunction is not called, but passed as an argument to the setTimeout function, whereas in line 4 myFunction is called; to call a function, you always have to use parentheses, even if there are no arguments.
I think this example would make it clearer if i may,
function callback() {
console.log('this function runs on page loads.');
}
setTimeout(callback(), 2000);
Here callback() function will run immediately after page loads and won't wait 2 seconds.
function callback() {
console.log('this function runs after page loads.');
}
setTimeout(callback, 2000);
Here callback() function will run after 2 seconds.

callback gets called before rest of the function executed

I recreated this example (from link given below) to understand callbacks. The problem is that the callback gets executed before the parent function 'first()' finishes. setTimeout works fine but callback doesn't wait until after the above . If i comment out line 1 and 3 of first() i.e. the timeout part, then it logs in the right order.
<script type="text/javascript">
function second() {
console.log("second/callback function")
}
function first(callback){
setTimeout(function(){
console.log("first function")
}, 1000 );
callback();
}
first(second);
If this is working fine and i misunderstand the nature of setTimeout, then please give another example where the callback can be seen waiting.
Link:
https://codeburst.io/javascript-what-the-heck-is-a-callback-aba4da2deced
Note: I know very little JS, was actually working in PHP, so kindly give a simple explanation. Thanks
It appears that you misunderstand how setTimeout() works. This tool called Loupe by Philip Roberts may help you understand. I've taken your code placed it into the tool which will allow you to visualise what is actually happening - link to Loupe
When you use setTimeout, that function provided as the first parameter is delayed for the number of milliseconds provided in the second parameter (in your example, this is 1000). The rest of your code will continue to execute in order until this timeout has lapsed.
If you want your callback function to execute after the given timeout: you can actually just write it such like:
setTimeout(callback, 1000) <- Since callback is already a function, you don't need to wrap it in another function unless you wish to do other operations before calling the callback.
Update 1 (2018-10-26):
function second() {
console.log("second/callback function")
}
function first(callback){
console.log("first function")
setTimeout(callback, 1000);
}
first(second);
Here you are calling "callback" synchronously which means first function will wait for second(callback) function to be completed and then proceed with it's execution. To understand it better I have put console log at other places as well. Pls try below and see if you now have better understanding for the same
function second() {
console.log('second method started')
setTimeout(() => console.log("second function executed"), 1000)
console.log('second method finished')
}
function first(callback){
console.log('first method started')
setTimeout(() => console.log("first function executed"), 1000 );
callback();
console.log('first method finished')
}
first(second);

Delay jquery function inside the function?

Is it possible to make a function 'idle' for a couple of seconds while it is being executed?
I tried with
setTimeout( function(){
$("#nytLevel").hide();
} , 3000 );
But the rest of the function would just executed.
Below the setTimeout I start a function
function timer(){
myVar = setTimeout( function(){
console.log("SLOW");
} , 10000 );
}
but when 10 seconds have passed it'll console log "SLOW", but it should console log it 13 seconds after because I've put a setTimeout to 3 seconds.
setTimeout() just schedules something to run in the future and the rest of your Javascript continues to run. It does not block further Javascript execution. This is often called an "asynchronous" operation. It runs in the background and will call a callback sometime in the future when it has completed its work. It is also referred to as "non-blocking" because it does not block the rest of your Javascript execution.
Anything you want to not run until the setTimeout() fires must be put inside the setTimeout() callback or called from there.
// define function
function timer(){
myVar = setTimeout(function() {
console.log("SLOW");
}, 10000);
}
// schedule first timer
setTimeout(function() {
$("#nytLevel").hide();
// now start second timer
timer();
}, 3000);
It's worth mentioning that jQuery has a .delay() method that works with animations and other functions put in the queue and it can sometimes streamline your code. In the case above, you could do this:
$("#nytLevel").delay(3000).hide().delay(10000).queue(function(next) {
console.log("SLOW");
next(); // keep the queue moving in case there's something else in the queue
});
Please note that .delay(xxx) only works with jQuery methods that themselves use the queue (such as animations) or with methods you put in the queue yourself using .queue() (as I've shown above).
setTimeout() is an asynchronous function, meaning that code will not pause until the setTimeout() time is completed. If you want code to be delayed along with the setTimeout(), you can put the other code inside of the initial setTimeout()
setTimeout( function(){
$("#nytLevel").hide();
myVar = setTimeout( function(){
console.log("SLOW");
} , 10000 );
} , 3000 );
I wouldn't recommend this, but you could fashion a recursive function to do what you wanted, using a flag to dictate before or after timeout. In the below example you'd call it like this runAfterTimeout() or runAfterTimeout(false)
function runAfterTimeout(run) {
if (! run) {
console.log('about to wait 10 seconds');
setTimeout(function(){runAfterTimeout(true)},10000);
return;
}
console.log('this section runs after 10 seconds');
setTimeout(function(){$("#nytLevel").hide();},3000);
}
Fiddle: https://jsfiddle.net/m9n1xxra/
Bear in mind, timeouts are not 100% accurate. The engine will look for an appropriate break in execution to execute what you want, but if the engine is in the middle of something else, that will execute first.

javascript function need to be continue after settimeout

I have a JavaScript function; from that am calling a delay function.
function(){
// code
doDelay();
// some other functionality....
}
function doDelay(){
setTimeout(function() {alert("after wait");}, 10000);
}
after waiting 10 seconds alert is coming after wait. but its not again continue the some other functionality.... of my main function.. After delay I want to execute the remaining functionality. How can I do that?
The setTimeout function does not delay execution. Instead, it schedules a function to be executed at a later time. To do what you want you need to change your code to this:
function(){
...
...
doDelay(function(){
some other functionality....
});
}
function doDelay(callback){
setTimeout(function() {callback()}, 10000);
}
Indeed, javascript already has a doDelay function. It's called setTimeout:
function(){
...
...
setTimeout(function(){
some other functionality....
},10000);
}
If you want the outer function to also delay execution of code that comes after it, you also need to pass a callback to it:
function foo (callback){
...
...
doDelay(function(){
some other functionality....
callback();
});
}
So that, for example, it allows you to rewrite something like this:
foo();
// do other stuff after foo...
to this:
foo(function(){
// do other stuff after foo...
});
You basically need to restructure your logic around callbacks.
Can't you wrap the other functionality in another function, then from your SetTimeout call that function?
function(){
doDelay();
}
function doDelay(){
setTimeout(function() {alert("after wait");andTheRest();}, 10000);
}
function andTheRest(){
//Rest of the stuff here
}
doDelayAndThenContinue(){
setTimeout(function() {alert("after wait");
//do other functionality here
}, 10000);
}
Remove the do other functionality from main method and put in setTimeout

Categories

Resources