Custom solution to implement callback function - javascript

Is it possible to wrap functions like setTimeout and then fire callback. Like in jQuery $(selector).on('action', callback).
var obj = {
mth1: function (callback) {
//----need to wrap to something
setTimeout(function () { console.log("1"); }, 1000);
console.log('2');
//----
// callback;
}
};
function callback() {
console.log('3');
};
(function () { obj.mth1(callback); }) ();
What I need:
2
1
3

Simply add it at the end of your function inside the setTimout
// *snip*
setTimeout(function () {
console.log("1");
callback();
}, 1000);
// *snip*

Not sure what you're asking for. Just make sure it is a function and call it:
mth1: function (callback) {
//----need to wrap to something
setTimeout(function () {
console.log("1");
// be sure it is a function
if (callback&& getType.toString.call(callback) == '[object Function]';) {
// call it
callback();
}
}, 1000);
console.log('2');
}

Related

How to execute code not from string using function?

How would I execute code not from a string? Here is an example:
var ready = false;
executeWhen(ready == true, function() {
console.log("hello");
});
function executeWhen(statement, code) {
if (statement) {
window.setTimeout(executeWhen(statement, code), 100);
} else {
/* execute 'code' here */
}
}
setTimeout(function(){ready = true}, 1000);
Could I use eval();? I don't think so, I think that's only for strings.
You call it with code().
You need to change statement to a function as well, so it will get a different value each time you test it.
And when you call executeWhen() in the setTimeout(), you have to pass a function, not call it immediately, which causes infinite recursion.
var ready = false;
executeWhen(() => ready == true, () =>
console.log("hello"));
function executeWhen(statement, code) {
if (!statement()) {
window.setTimeout(() => executeWhen(statement, code), 100);
} else {
code();
}
}
setTimeout(function() {
ready = true
}, 1000);

How to call a function after all setTimeout functions is done

How to call the second function after the all previous functions is done.
function first() {
// code here
setTimeout( function() {
// code here
}, 1000);
// code here
setTimeout( function() {
// code here
}, 3000);
// code here
setTimeout( function() {
// code here
}, 3800);
}
function second() {
// code here
}
first();
first();
second();
first();
second();
It seems all functions executed in the same time.
Thanks a lot.
If you need to call a specific function after the last timeout, I think this will point you in the right direction. Of course, it can be written better, with reusable "class" etc.
function myTimeout(f,t) {
var p = new Promise(resolve=>{
setTimeout(()=>{
resolve(f.apply(this,[]));
}, t);
});
//return p.promise();
return p;
}
function first() {
var numberOfTimeouts = 3
// code here
myTimeout(()=>{
// code here
console.log('a')
}, 1000).then(()=>{
numberOfTimeouts--;
if (!numberOfTimeouts) second()
});
// code here
myTimeout( function() {
console.log('b')
}, 3000).then(()=>{
numberOfTimeouts--;
if (!numberOfTimeouts) second()
});
// code here
myTimeout( function() {
console.log('c')
}, 3800).then(()=>{
numberOfTimeouts--;
if (!numberOfTimeouts) second()
});
}
function second() {
console.log('d')
}
first();

SetTimeout Executing faster then assigned interval

I have assigned 5000 ms to Settimeout but it is executing before assigned time interval.Can any body explain why it is happening.
<script type="text/javascript">
var getcallback = {
closure: function (callback, functionparam) {
return callback.call(functionparam);
}
}
var cleartimeout;
var startSlideShow = {
timerid: 5000,
startAnimation: function () {
cleartimeout = setTimeout(getcallback.closure(function () {
alert("this is a basic example of chaining methods");
this.startAnimation();
},this), this.timerid);
},
stopAnimation:function(){
}
}
startSlideShow.startAnimation();
</script>
Because getcallback.closure() is executing the function right away, you are not storing a reference to a function to call at a later time.
As soon as you call startAnimation, you're calling getcallback.closure, which immediately calls the callback function. To use setTimeout correctly, you need to either have closure return a function, or not use such a strange thing, and instead just use an anonymous function.
Something along the lines of:
var getcallback = {
closure: function (callback, functionparam) {
return function() {
callback.call(functionparam);
};
}
}
...
Or, to be cleaner, just:
var cleartimeout;
var startSlideShow = {
timerid: 5000,
startAnimation: function () {
cleartimeout = setTimeout(function () {
alert("this is a basic example of chaining methods");
this.startAnimation();
}, this.timerid);
},
stopAnimation:function(){
}
}
startSlideShow.startAnimation();

Chaining ajax requests with jQuery's deferred

I have a web app which must call the server multiple times. So far, I had a long nested callback chain; but I would like to use jQuery's when,then etc. functionality. However, I can't seem to get stuff running again after using a then.
$
.when ($.get('pages/run-tool.html'))
.then (function (args)
{
// This works fine
alert(args);
$('#content').replaceWith (args);
$('#progress-bar').progressbar ({value: 0});
})
.then ($.get('pages/test.html'))
.done (function(args)
{
// This prints the same as the last call
alert (args);
});
What am I doing wrong? I guess its some scoping issue, as I can see the second get call being executed. Using two different args variables does not help as the argument passed to the done function is still the first get request.
As an update:
With modern jquery (1.8+) you don't need the preliminary when because get returns a Deferred Promise.
Also, pipe is deprecated. Use then instead. Just be sure to return the result of the new get which becomes the Promise attached to by subsequent then/*done*/fail calls.
So:
$.get('pages/run-tool.html')
.then (function (args) { // this will run if the above .get succeeds
// This works fine
alert(args);
$('#content').replaceWith (args);
$('#progress-bar').progressbar ({value: 0});
})
.then (function() { // this will run after the above then-handler (assuming it ran)
return $.get('pages/test.html'); // the return value creates a new Deferred object
})
.done (function(args) { // this will run after the second .get succeeds (assuming it ran)
alert (args);
});
All three callbacks (the two with then and the one with done) are applied to the same request – the original when call. This is because then returns the same Deferred object, rather than a new one, so that you can add multiple event handlers.
You need to use pipe instead.
$
.when ($.get('pages/run-tool.html'))
.then (function (args)
{
// This works fine
alert(args);
$('#content').replaceWith (args);
$('#progress-bar').progressbar ({value: 0});
})
.pipe (function() {
return $.get('pages/test.html'); // the return value creates a new Deferred object
})
.done (function(args)
{
alert (args);
});
Here is an wonderfully simple and highly effective AJAX chaining / queue plugin. It will execute you ajax methods in sequence one after each other.
It works by accepting an array of methods and then executing them in sequence. It wont execute the next method whilst waiting for a response.
//--- THIS PART IS YOUR CODE -----------------------
$(document).ready(function () {
var AjaxQ = [];
AjaxQ[0] = function () { AjaxMethod1(); }
AjaxQ[1] = function () { AjaxMethod2(); }
AjaxQ[3] = function () { AjaxMethod3(); }
//Execute methods in sequence
$(document).sc_ExecuteAjaxQ({ fx: AjaxQ });
});
//--- THIS PART IS THE AJAX PLUGIN -------------------
$.fn.sc_ExecuteAjaxQ = function (options) {
//? Executes a series of AJAX methods in dequence
var options = $.extend({
fx: [] //function1 () { }, function2 () { }, function3 () { }
}, options);
if (options.fx.length > 0) {
var i = 0;
$(this).unbind('ajaxComplete');
$(this).ajaxComplete(function () {
i++;
if (i < options.fx.length && (typeof options.fx[i] == "function")) { options.fx[i](); }
else { $(this).unbind('ajaxComplete'); }
});
//Execute first item in queue
if (typeof options.fx[i] == "function") { options.fx[i](); }
else { $(this).unbind('ajaxComplete'); }
}
}
The answer cdr gave, which has the highest vote at the moment, is not right.
When you have functions a, b, c each returns a $.Deferred() object, and chains the functions like the following:
a().then(b).then(c)
Both b and c will run once the promise returned from a is resolved. Since both then() functions are tied to the promise of a, this works similiar to other Jquery chaining such as:
$('#id').html("<div>hello</div>").css({display:"block"})
where both html() and css() function are called on the object returned from $('#id');
So to make a, b, c run after the promise returned from the previous function is resolved, you need to do this:
a().then(function(){
b().then(c)
});
Here the call of function c is tied to the promise returned from function b.
You can test this using the following code:
function a() {
var promise = $.Deferred();
setTimeout(function() {
promise.resolve();
console.log("a");
}, 1000);
return promise;
}
function b() {
console.log("running b");
var promise = $.Deferred();
setTimeout(function () {
promise.resolve();
console.log("b");
}, 500);
return promise;
}
function c() {
console.log("running c");
var promise = $.Deferred();
setTimeout(function () {
promise.resolve();
console.log("c");
}, 1500);
return promise;
}
a().then(b).then(c);
a().then(function(){
b().then(c)
});
Change the promise in function b() from resolve() to reject() and you will see the difference.
<script type="text/javascript">
var promise1 = function () {
return new
$.Deferred(function (def) {
setTimeout(function () {
console.log("1");
def.resolve();
}, 3000);
}).promise();
};
var promise2 = function () {
return new
$.Deferred(function (def) {
setTimeout(function () {
console.log("2");
def.resolve();
}, 2000);
}).promise();
};
var promise3 = function () {
return new
$.Deferred(function (def) {
setTimeout(function () {
console.log("3");
def.resolve();
}, 1000);
}).promise();
};
var firstCall = function () {
console.log("firstCall");
$.when(promise1())
.then(function () { secondCall(); });
};
var secondCall = function () {
console.log("secondCall")
$.when(promise2()).then(function () { thirdCall(); });
};
var thirdCall = function () {
console.log("thirdCall")
$.when(promise3()).then(function () { console.log("done"); });
};
$(document).ready(function () {
firstCall();
});
</script>
I thought I would leave this little exercise here for anyone who may find it useful, we build an array of requests and when they are completed, we can fire a callback function:
var urls = [{
url: 'url1',
data: 'foo'
}, {
url: 'url2',
data: 'foo'
}, {
url: 'url3',
data: 'foo'
}, {
url: 'url4',
data: 'foo'
}];
var requests = [];
var callback = function (result) {
console.log('done!');
};
var ajaxFunction = function () {
for (var request, i = -1; request = urls[++i];) {
requests.push($.ajax({
url: request.url,
success: function (response) {
console.log('success', response);
}
}));
}
};
// using $.when.apply() we can execute a function when all the requests
// in the array have completed
$.when.apply(new ajaxFunction(), requests).done(function (result) {
callback(result)
});
My way is to apply callback function:
A(function(){
B(function(){
C()})});
where A, B can be written as
function A(callback)
$.ajax{
...
success: function(result){
...
if (callback) callback();
}
}

javascript jquery: call function with parameters after timeout?

How can I call a function like this with parameters applied to it?
searchTimer = setTimeout(doSearch, 250);
function doSearch(parameter) {
}
Use an anonymous function as a wrapper:
searchTimer = setTimeout(function () {
doSearch('parameter');
}, 250);

Categories