Add delay between two functions in reactjs - javascript

I have two functions and I need a forced delay between those two consecutive function calls. That is to say,
a // call func a
delay(100) // delay for 100 ms
b // call func b
Is there anyway to do so?
Edit: tried
a();
console.log("a");
setTimeout(b(), 1000);
console.log("b");

With new ES6, you can even make it more cleaner and look like sequential,
function delay(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
})
}
async function doItHere() {
console.log('a', Date.now());
await delay(5000);
console.log('b', Date.now())
}
doItHere();

All you need to do is to make use of setTimeout function to call b after calling a
a() // call func a
setTimeout(b, 100) // delay for 100 ms
if you need to keep b function bound to the current scope, use:
setTimeout(() => b(), 100) // () => {} functions are always bound to the current scope

Try this:
a() // First call function a
Then call function b in setTimeout function.
es5:
setTimeout(function() {b()},100);
es6:
setTimeout(()=> {b()},100);

Related

How to react on function that setting timeout

I have function:
function a(){ setTimeout(()=>{console.log('a')}, 0) }
This function send console.log on very end of callstack isn't it?
How can I write a function that runs after this console.log
the only way i found is send function on the of of callstack in the same way
a();
setTimeout(()=>{ console.log('after a'), 0 });
But it looks bad for me. I tried with promise, but i can react then on 'a' function not on console.log inside.
function 'a' is uneditable
you can use "callback" , a reference to another function to the a( ) function. Example:
function yourFunctionToBeRunnedAfter(){
..
..
}
function a(callback){
setTimeout(()=>{
console.log('a');
calback(); // ==> here is your function execution.
}, 0);
}
a(yourFunctionToBeRunnedAfter);
if you have parameters to pass to the callback() call, you can use apply() or call() or bind() or the spread operator (...) example:
function a(callback,...params){ // ... is the spread operator
setTimeout(()=>{
console.log('a');
callback([...params]); // ==> here is your function execution by spreading your params to the callback call.
}, 0);
}
a(yourFunctionToBeRunnedAfter, 1,2,3);
You need to use a promise. I'd recommend using async-await, but it really depends on your preference.
function a () {
return new Promise(resolve => {
setTimeout(() => {
console.log('a')
resolve()
}, 0)
})
}
a().then(() => console.log('after a'))
If you need to know when timeouts finish often, I'd recommend making a helper function:
const wait = (time) => new Promise(r => setTimeout(r, time))
Then you can use it like so:
(async () => {
console.log('Hello')
await wait(1000) // wait 1 second
console.log('Hello a second later')
})()

Why does this simple callback execute before the setTimeout?

This snippet logs 'output 2' ahead of 'output 1', which is cool due to the setTimeout.
const func1 = () => {
setTimeout(() => {
console.log('output 1');
}, 3000);
};
const func2 = () => {
console.log('output 2');
};
func1();
func2();
In this snippet, I used a callback, but it gave me the same result as the last snippet, why doesn't func1 execute before func2? How can I make func2 execute after func1?
const func1 = () => {
setTimeout(() => {
console.log('output 1');
}, 3000);
};
const func2 = () => {
console.log('output 2');
};
const main = (a, b) => {
a();
b();
};
main(func1, func2);
why doesn't func1 execute before func2
It does.
Func1 sets a timeout running
Func2 logs
3 seconds later the callback function you pass to setTimeout is called
If you want to make Func2 run after step 3, then you need to call it at the end of the callback you pass to setTimeout.
JavaScript does not wait for setTimeout to finish and then execute next functions.
whenvever javascript encounters a setTimeOut it store functions with provided timeout, in this case 3 seconds. after storing it in call stack it just starts to execute functions below it and since there is nothing in second function it get executed right away ( before 3 seconds obviously ). that's why you are seeing the log of second function before the log of first function.
To execute first function and then execute second function you can use promise chaining.
Example:
return new Promise(function(resolve, reject) {
setTimeout(() => {
console.log('output 1');
resolve();
}, 3000);
}).then(function(result) {
console.log('output 2');
});
Hope it will help. Feel free to correct if i am wrong.
Simple explanation -
Function 2 wouldn't wait for the completion of the timer started in function 1.
func1();
func2();
When you execute both functions, function 1 sets the timer and function 2 logs out.
Eventually, function 1 logs out after 3 seconds.
Your second snippet does pretty much the same.

passing another function as dot operator in js like A.mainFunction(parm1,parm2,parm3)

I have a function A which let say perform addition,
function A(a,b){
return a+b;
}
now I need to create another function which calls the function A after some time as follows.
A.callFunction(1000,1,2) //where 1000 is the time interval after which A needs to be called and 1,2 are the values which will be passed in A function.
How can I achieve this? And what is its significance.
Therefore, callFunction would be a function that enables ANY function (A) to be called after some specified duration, like the above mentioned format.
Your main function is like bellow
function A(param1, param2) {
console.log("I am executed");
return param1 + param2;
}
The calling function is like bellow
function CallMe(timeInterval, param1, param2, callBackFunction) {
setTimeout(() => {
callBackFunction(param1, param2);
}, timeInterval);
}
Call it anywhere like this
CallMe(10000, 1, 2, A);
at first, it will go to the CallMe() function for setTimeout() it will wait what the time interval you will pass to the function
I think it can be achieved using setTimeout or setInterval (for recurring needs)
Example
function A(a,b){
alert(a+b);
}
setTimeout(function() { A(1, 2) }, 3000);
setInterval(function() { A(1, 2) }, 3000); //for recurring needs
the second parameter is in ms so 3000ms means 3s
You can do this by:
Adding a new property to the function prototype to apply to all functions, and
Using the spread operator (...) to dynamically pass in all parameters from the deferred function to the originnal.
Using setTimeout to defer the execution of the function
This is an example using Promise:
Function.prototype.defer = function(delay, ...args) {
return new Promise(resolve => setTimeout(() => {
resolve(this(...args));
}, delay));
}
function add(a, b){
return a + b;
}
function subtract(a, b){
return a - b;
}
console.log('add immediate', add(1, 2));
add.defer(1000, 3, 4)
.then(result => console.log('add delayed', result));
console.log('subtract immediate', subtract(2, 1));
subtract.defer(1000, 6, 4)
.then(result => console.log('subtract delayed', result));

How to call two async functions every `n` and `m` seconds within a `while (true)` loop?

I have the following loop:
while (true) {
await f();
await g();
}
where f and g are defined as follows:
async function f() {
await Promise.all([SOME_REQUEST_F, sleep(1000)])
}
async function g() {
await Promise.all([SOME_REQUEST_G, sleep(5000)])
}
Also sleep is defined as follows:
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
My intention is to have SOME_REQUEST_F awaited every one second, and SOME_REQUEST_G awaited every five seconds, hence wrapping them in f and g.
However, currently g is blocking the re-awaiting of f within the loop.
How to define sleep, such that if used in g, it blocks re-execution of g, but not that of f? Is there a better way to do what I want?
Use two while loops instead:
(async () => {
setTimeout(async () => {
while (true) {
await f();
}
});
while (true) {
await g();
}
})();
The setTimeout there is needed to allow both whiles to run concurrently, so that the initialization of one doesn't block the other from starting.

Create a function that no matter how many times invoked run only when first async call finishes?

suppose I've a function fetch(id).
I would be calling it arbitrarily at random times.
But I want every successive call to run only after previous call has finished.
say the async task takes 4 seconds, and i call fetch 3 times. then total time should be 12 seconds.
I could make a array and at every call set promise to go through next in line.
but what are some ways to accomplish this.
I think I got it
//First my example function which could be anything but should return promise which would be queued
function example(n) {
return new Promise((res, rej) => {
setTimeout(()=> {
console.log(n);
res();
}, 1000);
});
}
//now solution
function debounce(func) {
let p = Promise.resolve();
return function(x){
p = p.then(() => func(x));
}
}
//usage
d = debounce(example);
d(1);d(2);d(3);d(4);d(5);d(6);d(1);
You can chain Promises without an array, just store a pointer to the last Promise
// async payload function
// returns a promise
function f(x) {
console.log(`call f(${x})`);
return new Promise((resolve) => {
setTimeout(() => {
console.log(`resolve f(${x})`);
resolve();
}, 2000);
});
}
// wrapper to call function `f` sequentially
// stores pointer to the last Promise in closure
const g = (function(){
let lastPromise = Promise.resolve();
return function(arg){
lastPromise = lastPromise.then(() => f(arg));
}
})();
// generate random calls of function function `g`
for (let i = 0; i < 5; i++) {
setTimeout(() => g(i), Math.random() * 100);
}
I guess you can use async.io library.
Or, each time you want to call your function, push the function itself in an array. When the previous function has finished, check if there is still some functions to call in the array.

Categories