How to use function in settimeout for milliseconds in javascript [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I use an ajax call to get the value of timer from the server. And I have to use that value for timeout in setTimeout() method. How to use functions instead of an actual value.
Here is my code:
if(isStopped) {
setTimeout(stopLoading, getTimerValue());
console.log("Stopped loading image");
}
getTimerValue() is my ajax call to the server. It works fine if I use an value like 5000 instead of the function. Please help me to solve this. Thanks in advance!
Update - Solved:
There was an issue with my ajax call. It was returning undefined. After adding callback option, it works fine.

Please check this example.
var isStopped = true;
function getTimerValue() {
return 5000;
}
function stopLoading() {
console.log('ok')
}
if(isStopped) {
setTimeout(stopLoading, getTimerValue());
console.log("Stopped loading image");
}
As i set isStopped to true so its insert the if condition then its set the setTimeout function. but as i set it to execute it after 5000 so it will wait in the mean time it will execute the next line console.log("Stopped loading image"); and the after 5000 it prints ok
Hope This will help

Related

The difference between using setTimeout(fn, 0) and not using it [duplicate]

This question already has answers here:
Why is setTimeout(fn, 0) sometimes useful?
(19 answers)
Closed 3 years ago.
I have a simple question about setTimeout function
My function:
function myFunc(){
// some code here
}
What's different when
I call a function with and without setTimeout:
myFunc();
setTimeout(function(){
myFunc();
}, 0);
Can someone explain help me? Thank you.
setTimeout waits for a given delay then schedules a new task for its callback. This is why setTimeout is logged after script end, as logging script end is part of the first task, and setTimeout is logged in a separate task. Right, we're almost through this, but I need you to stay strong for this next bit…
Tasks are scheduled so the browser can get from its internals into JavaScript/DOM land and ensures these actions happen sequentially. Between tasks, the browser may render updates. Getting from a mouse click to an event callback requires scheduling a task, as does parsing HTML, and in the above example, setTimeout.
https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/
setTimeout(,0) will call after all current queue will be finished, and
normal function call goes in the queue first.
You can see here:
function myFunc1(){
console.log("In myFunc1");
}
function myFunc2(){
console.log("In myFunc2");
}
setTimeout(function(){
myFunc1();
}, 0);
myFunc2();

Dealing with slow callback functions [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 6 years ago.
When getting data from a text file, it seems to take a while. With the first console.log the result is undefined, after waiting some time and then running console.log the data shows.
var msg;
$.get("./whazzup.txt", function(text) {
msg = text;
});
console.log(msg);
setTimeout(function(){ console.log(msg); }, 3000);
How would I go about only running code once the callback is complete?
Just move the console.log() into the "done" callback function because you can't know exactly when or if it will complete. This is the point of the "done" callback function - - to defer work that needs to be done after a successful call has been made.
JavaScript promises (or JQuery deferreds) could also be used to disconnect the callback(s) from the initial AJAX request for more flexibility, but the nature of AJAX stays the same.
$.get("./whazzup.txt", function(text) {
// This function will only be executed when the AJAX call has successfully completed
msg = text;
console.log(msg);
});
// This one was working, because you are basically telling the JavaScript
// runtime to wait 3 seconds (at least) before writing the message and by
// that time the AJAX call has completed. But, this technique is not
// reliable because there may be times when the AJAX call hasn't completed
// after 3 seconds. You just can't know how long it will take.
setTimeout(function(){ console.log(msg); }, 3000);

How to ensure synchronous loading in angularjs app.js [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
So i have this code
getTens.getToken($rootScope.webUserInfo[0].username).then(function(resulttoken) {
$rootScope.userInfo = resulttoken;
$sessionStorage.token = resulttoken[0].token;
$sessionStorage.userInfoStorage = $rootScope.userInfo;
CasesGroupByCaseStatus.getListing($rootScope.webUserInfo[0].username).then(function(data){
$rootScope.listingDetails = data;
$sessionStorage.listingDetailsStorage = $rootScope.listingDetails;
});
CasesGroupByCaseStatus.caseStatusCount($rootScope.webUserInfo[0].username).then(function(resultcaseStatus){
$rootScope.dashboardStatus = resultcaseStatus;
$sessionStorage.dashboardStatusStorage = $rootScope.dashboardStatus;
console.log("it is finished")
});
});
return [200, { authorizationToken: $sessionStorage.token}];
In my code, i want it to complete the function first before returning the value but what happens is that it fires the return first wtout running the function, How do i handle this?
This code is my app.js. So i cant do stuffs such as scope.watch and all.
I'm not sure if this is a good way to solve the problem, but for my application I put a
$rootScope.$broadcast('loaded', true);
inside the asynchronous part's callback/success function
and then put my code inside this:
$scope.$on('loaded', function(){ //everything is loaded });
Like I said, not sure if this is a good solution or not. I used this to make my application wait for a asynchronous function to finish reading a file before starting my application. Some answer is better than no answer I guess.

how can i get return value of javascript function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How to return AJAX response Text? [duplicate]
(2 answers)
Closed 8 years ago.
my code like this
var key,value;
//……some code……
function checkReg(i,j){
$.getJSON(api_checkExists,{"k":i,"v":j,"rand":Math.random()},function(c){
alert(c.status);
return(c.status);
});
}
var temp=checkReg(key,value);
alert(temp);
The problem is when I run it in my browser, it always fist alert undefined then alert the return value; seems like that can not get the return value of function checkReg. I was so confused, what should I do?
That's because your ajax call is running asynch from the rest. Your code will already have returned before before the ajax is even triggered.
So the returning doesn't work like that, you should provide a callback to your function instead of trying to return it.
function checkReg(i,j, callback){
$.getJSON(api_checkExists,{"k":i,"v":j,"rand":Math.random()},function(c){
alert(c.status);
callback(c.status);
});
}
checkReg(key,value, function(temp){
alert(temp);
});
you cannot do that... since ajax is ashynchronus ... by the time the success function is called and return, the alert will be called thus having temp as undefined or empty.. one way to do this is doing the thing you need to inside the success called back of getJSON... or use $.deffered or callinga calback function..
function checkReg(i,j, callback){
$.getJSON(api_checkExists,{"k":i,"v":j,"rand":Math.random()},function(c){
callback(c.status);
});
}
checkReg(key,value, function(temp){
alert(temp);
});

Get variable out of a multiple nested functions [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I'm trying to get a variable (lib) out of a multiple nested functions.
var nme='name',lib;
$('script').each(function(){
var src=$(this).attr('src');
if(typeof(src)==='undefined'){src='';}
if(src.indexOf(nme)!==-1){
$.get($(this).attr('src').match(/\w([^ ]+)spbin/)[0]+'/conf/ptmedia.plist',
function(c){
$(c).find('key').each(function(){
if($(this).html()==='MediaLib'){lib=$(this).next().html();}
});
}
);
}
});
if(lib==='some lib'){DO STUFF}
Your problem isn't with scoping, the problem is that you have an AJAX call which is asynchronous.
You should put the change of HTML in .null inside the callback function instead:
$.get($(this).attr('src').match(/\w([^ ]+)spbin/)[0]+'/conf/ptmedia.plist',
function(c){
$(c).find('key').each(function(){
if($(this).html()==='MediaLib'){lib=$(this).next().html();}
$('.null').html(lib);
});
}
});
In JavaScript often IO is asynchronous. This means that when you make an AJAX call it does not happen immidiately but rather waits for the value to return from the HTTP request and then calls a callback. In your case that function(c) is the callback, it gets executed when the value of the AJAX call arrived.
So in fact you were updating the HTML content of .null to undefined, since it got the value of lib before it was updated.
I solved this problem as follows:
var nme='name';
$('script').each(function(){
var src=$(this).attr('src');
if(typeof(src)==='undefined'){src='';}
if(src.indexOf(nme)!==-1){media=$(this).attr('src').match(/\w([^ ]+)spbin/)[0];}
});
function ffn(){
$($.ajax({url:media+'/conf/ptmedia.plist',async:false}).responseText).find('key').each(function(){
if($(this).html()==='string'){value=$(this).next().html();}
});
return value;
}
if(ffn()==='some lib'){DO STUFF}
Thank you all for your participation and good ideas!

Categories

Resources