Get return value from setTimeout [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
The community is reviewing whether to reopen this question as of 9 days ago.
I just want to get the return value from setTimeout but what I get is a whole text format of the function?
function x () {
setTimeout(y = function () {
return 'done';
}, 1000);
return y;
}
console.log(x());

You need to use Promises for this. They are available in ES6 but can be polyfilled quite easily:
function x() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('done!');
});
});
}
x().then((done) => {
console.log(done); // --> 'done!'
});
With async/await in ES2017 it becomes nicer if inside an async function:
async function() {
const result = await x();
console.log(result); // --> 'done!';
}

You can't get a return value from the function you pass to setTimeout.
The function that called setTimeout (x in your example) will finish executing and return before the function you pass to setTimeout is even called.
Whatever you want to do with the value you get, you need to do it from the function you pass to setTimeout.
In your example, that would be written as:
function x () {
setTimeout(function () {
console.log("done");
}, 1000);
}
x();

Better to take a callback for function x and whatever task you want to perform after that timeout send in that callback.
function x (callback) {
setTimeout(function () {
callback("done");
}, 1000);
}
x(console.log.bind(console)); //this is special case of console.log
x(alert)

You can use a combination of Promise and setTimeOut like the example below
let f1 = function(){
return new Promise(async function(res,err){
let x=0;
let p = new Promise(function(res,err){
setTimeout(function(){
x= 1;
res(x);
},2000)
})
p.then(function(x){
console.log(x);
res(x);
})
});
}

I think you want have flag to know event occured or no. setTimeout not return a value. you can use a variable to detect event occured or no
var y="notdone";
setTimeout(function () {
y="done";
}, 1000);
You can access variable y after timeout occured to know done or not

Related

javascript wait until variable is set [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 months ago.
Can you make a function wait until a variable is set by another function? This is my example:
function setvar(){
//some process that may take a while
myvar = 'value';
}
const promise1 = new Promise((resolve, reject) => {
resolve(myvar);
});
promise1.then((value) => {
console.log(value);
});
this doesnt seem to work, the function begins even if the variable is not ready. What should I do? I dont want settimeout or setinterval because I dont know exactly how long it is going to take each time.
In the promise you'll need create a loop that would check if variable was set:
var myvar;
function setvar(){
//some process that may take a while
myvar = 'value';
}
const promise1 = new Promise((resolve, reject) => {
const loop = () => myvar !== undefined ? resolve(myvar) : setTimeout(loop)
loop();
});
promise1.then((value) => {
console.log(value);
});
setTimeout(setvar, 2000);

NodeJS: Assign the value inside a callback function to a variable outside of it [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 1 year ago.
I want to assign the value inside a callback function to a variable outside of it. Here is an example with child_process.
callback.js
let variable;
require('child_process').spawn('python', ['./hello.py']).stdout.on('data', data => {
variable = data.toString();
console.log(variable);
});
console.log(variable);
hello.py
print('Hello World')
output:
undefined
Hello World
I know that the console.log at the bottom is being executed before the callback function and therefore the variable is still undefined. But how could I wait for the callback function to finish first?
Solution:
Promises seem to be the optimal answer and the code needs to be asynchronous.
async function test() {
const promise = new Promise((resolve, reject) => {
require('child_process').spawn('python', ['./test.py']).stdout.on('data', data => {
resolve(data.toString());
});
});
return promise;
}
(async function () {
let variable;
await test().then(res => {
variable = res;
});
console.log(variable);
}())
You can use a promise to wait for the callback like in this example:
let data;
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
data="abc";
resolve('foo');
}, 300);
});
myPromise.then((res)=>{console.log(data+res)})
this will print out "abcfoo"
Often the best way to wait for something asynchronous is to have asynchronous code yourself.

delay function return until a value is set [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
i have a function , i need to delay its return until a value is set (by calling another function call_api basically i need to wait for second function result to be able to return the first function result )
here is what ti got
function getList(s, p)
{
var output = false ;
call_api(s , p , function(result){
console.log(result);
output = result;
})
while (output == false )
{
1 ;
}
return output ;
}
but it wont work while somehow is messing thing up
is there a way to solve this ?
ps : i know about promise / async function but i cant use them (its a test i ant use them in the test )
You could do it using Promises, using a callback, or by checking the value every interval, using setTimeout. You can't do otherwise by definition of the Javascript language.
Using promises:
async function getList(s, p) {
return await new Promise(resolve => call_api(s, p, result => resolve(result)));
}
Using callback:
var output = false;
call_api(s, p, result => {
output = result;
callback();
});
function callback() {
// rest of code
}
Using setTimeout:
var output = false;
call_api(s, p, result => output = result);
checkOutput();
function checkOutput() {
if (output === false) {
setTimeout(checkOutput, 100);
} else {
// rest of code
}
}

Javascript How do I wait x seconds before running next line of code? [duplicate]

This question already has answers here:
Wait 5 seconds before executing next line
(13 answers)
Closed 5 years ago.
I would like to be able to make something similar to this:
function testFunction() {
alert("Test");
}
if (x > y) {
wait(z);
testFunction();
}
Thanks!
Can now nicely be done with promises:
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function demo() {
console.log('Taking a break...');
await sleep(2000);
console.log('Two second later');
}
demo();
Please try using the setTimeout function:
setTimeout(function(){ alert("Hello"); }, 3000);
From this link:
https://www.w3schools.com/jsref/met_win_settimeout.asp
So for your specific use case:
var timeToWait = 3000; // in miliseconds.
function testFunction() {
alert("Test");
}
if (x > y) {
setTimeout(function(){ testFunction(); }, timeToWait);
}
Hope that helps.
You have to put your code in the callback function you supply to setTimeout:
function stateChange(newState) {
setTimeout(function () {
if (newState == -1) {
alert('VIDEO HAS STOPPED');
}
}, 5000);
}
From this question: Javascript - Wait 5 seconds before executing next line

Javascript settimeout + callback [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I have a javascript question relating to callback and timeout.
This is an example code snippet I wrote:
var f1 = function(){
var result;
window.setTimeout(
function(){
console.log("timeout in 100ms");
result = 10;
}.bind(this), 100);
return result;
};
So, I want the function to modify the variable result. I used .bind(this) to ensure that it knows what result it.
still, the out put when I run f1() is 9, not 10, which is what I have desired.
Any clues?
Result is a number. Therefore it is returned as the value 9 not a reference to an object.
bind does not have any useful effect in your scenario. bind changes the function context (this).
Returning an object containing the value 10 will work.
var f1 = function(){
var result = { value: 9 };
window.setTimeout(
function(){
console.log("timeout in 100ms");
result.value = 10;}.bind(this), 100);
return result;
};
There are likely better solutions to your problem.
Callbacks:
var f1 = function(valueCallback){
var result;
window.setTimeout(function(){
console.log("timeout in 100ms");
result = 10;
valueCallback(result);
};
Such a function would be used like so:
f1(function(value)) {
console.log(value); // Will print 10 after 100ms.
})
Another alternative, could use Promises:
var f1 = function() {
return new Promise(function(resolve, reject) {
window.setTimeout(resolve.bind(null, 10), 100);
}
}
You would call such a function like so:
f1().then(function(value) {
console.log(value); // Will print 10 after 100ms.
});
You are calling the timeout to modify the value after the function already returned, so it returns the default value for result, then call the timeout, and since the value is limited in scope to the function, you have no means to return it after modification.
What you can do is this
var result = 9;
var f1 = function(){
window.setTimeout(
function(){
console.log("timeout in 100ms");
result = 10;}.bind(this), 100);
return result;};
And then after calling f1 t will return 9 then call result and it will show 10

Categories

Resources