javascript function need to be continue after settimeout - javascript

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

Related

JavaScript: stop execution untill delay is over

My code is something like this:-
function doStuff(){
// Note:- this funcion take 50ms for ececution as i have put
// timeout
setTimeout(function(){
// some line of code
....
}, 50);
return;
}
doStuff();
console.log('This should execute after doStuff() complete its work.")
// after that more many lines of code and more stuff are here
.....
.....
Now what I want is, as you can see here that doStuff() takes 50ms of time to execute so the code which is after doStuff() it should execute after doStuff() complete it's work. For example, that console should print after doStuff() is completed.
Note that I know I can put timeOut there, but I can't put timeout because of some limitations as I am working on an opensource project so I can't change code which is written after that function call, i can't even wait for promise as i told i can't change that code what I can do is change the doStuff method I have made that method. Is there any way to stop doStuff() return, like doStuff() should not return until that delay is over, one way is we can recursively call doStuff but I want the better way to do that. Please help me out.
You either need to use callbacks, or promises. Here's an example of promises:
function doStuff(){
var promise = new Promise((resolve) => {
// Note:- this funcion take 50ms for ececution as i have put
// timeout
setTimeout(function(){
// some line of code
resolve();
}, 1000);
});
return promise;
}
async function main() {
console.log('Start.');
await doStuff();
console.log('This should execute after doStuff() complete its work.');
}
main();
Alternatively, use .then() of promises, if you don't want to use the nice async/await functionality that ES6 brings:
function doStuff(){
var promise = new Promise((resolve) => {
// Note:- this funcion take 50ms for ececution as i have put
// timeout
setTimeout(function(){
// some line of code
resolve();
}, 1000);
});
return promise;
}
console.log('Start.');
doStuff().then(() => console.log('This should execute after doStuff() complete its work.'));
Here's an example of using callbacks:
function doStuff(callback){
setTimeout(function(){
// some line of code
callback();
}, 1000);
}
console.log('Start.');
doStuff(function() {
console.log('This should execute after doStuff() complete its work.');
});

call function periodically in javascript until finished, then start calling different function

I have two functions on my page that I need to call periodically, but in a certain way only.
function_a needs to be run periodically when the page loads, until data is available and downloaded.
After this point, function_b then needs to run periodically forever.
I can easily do...
setInterval(function_a, 1000);
setInterval(function_b, 5000);
But this will run both functions from the start of page load and forever.
How can I stop function_a running once I have determined that it is not needed anymore, and only start function_b running after this point?
I can put checks within the function_a and function_b code so that they dont execute if not needed, but it seems very wasteful to still call them continually when they are not needed.
function_a(){
if (needed) { code here... }
}
function_b(){
if (needed) { code here... }
}
There must be a better way than that?
Instead of a setInterval here, setTimeout will work far better.
function a() {
//do stuff
if(condition) setTimeout(b, 5000)
else setTimeout(a, 1000)
}
function b(){
//do stuff
setTimeout(b, 5000)
}
a()
This way, the function will execute and schedule itself to run again on the desired interval. This is similar to the way requestAnimationFrame is used for creating animations.
You can assign a variable to setInterval() call and use clearInterval()
let a = setInterval(function_a, 1000);
function_b() {
if (a_is_not_needed) { clearInterval(a) }
}
Use clearInterval() to stop a function called in a setInterval()
var needed = false;
var f1 = function(){
console.log("Fct1");
if(needed){
setInterval(f2, 5000); // start f2 when f1 is finish
clearInterval(interval); // stop to call periodically f1
}
}
var f2 = function(){
console.log("Fct2");
}
var interval = setInterval(f1, 1000);
Try this fiddle and open console to see the result

Settimeout just after a function

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

To delay JavaScript function call using jQuery

JavaScript:
$(document).ready(function(){
function sample() {
alert("This is sample function");
}
$("#button").click(function(){
t = setTimeout("sample()",2000);
});
});
HTML:
<input type="button" id="button" value="Call sample function with delay">
Once I click the button, sample() function is not called with a delay of 2 seconds. I don't know what's wrong.
How to call JavaScript function using setTimeout() via jQuery?
Since you declare sample inside the anonymous function you pass to ready, it is scoped to that function.
You then pass a string to setTimeout which is evaled after 2 seconds. This takes place outside the current scope, so it can't find the function.
Only pass functions to setTimeout, using eval is inefficient and hard to debug.
setTimeout(sample,2000)
function sample() {
alert("This is sample function");
}
$(function() {
$("#button").click(function() {
setTimeout(sample, 2000);
});
});
jsFiddle.
If you want to encapsulate sample() there, wrap the whole thing in a self invoking function (function() { ... })().
Very easy, just call the function within a specific amount of milliseconds using setTimeout()
setTimeout(myFunction, 2000)
function myFunction() {
alert('Was called after 2 seconds');
}
Or you can even initiate the function inside the timeout, like so:
setTimeout(function() {
alert('Was called after 2 seconds');
}, 2000)

Javascript timing problem

I wont to run a block of code in a certain amount of time and then when done, carry on with another block of code.
Using the setTimeout() is probably what you want. For example...
<script type="text/javascript">
function YourFunction()
{
alert('Hello Stackoverflow');
}
window.setTimeout(YourFunction, 1000);
</script>
Hope it helps
This is how you would do it, using the setTimeout function, which takes code to call as the first argument and how much time it should wait before calling it (in milliseconds) as the second argument:
function callWhenDone() {
// code to call when timeout finishes
}
setTimeout(function() {
// initial code to run
callWhenDone();
}, 5000); // 5000 = run in 5 seconds
Because of the nature of Javascript you have to encapsulate the code you want to run after the timeout is finished in its own function, otherwise it would be run before the timeout is finished. This is, in essense, a callback, and it is a big part of the event-based nature of Javascript.
You'll want to use the setTimeout() function.
setTimeout - executes code after a time interval
clearTimeout - cancels the setTimeout()
More details here.
Use setTimeout.
setTimeout(function() {
// code here
// you can use it recursively
// setTimeout(...);
},
1000 // 1000 miliseconds (= 1 second)
);
and setInterval is like setTimeout, except it repeats a code repeatedly.
<script type="text/javascript">
var timer = setInterval("firstFunction()","1000"); //every second call firstFunction()
var i = 0;
function firstFunction()
{
//first code
i++;
if(i == 3)
{
clearInterval(timer);
secondFunction();
}
}
function secondFunction()
{
//second code
alert("done!");
}
</script>

Categories

Resources