I have a simple "async" JS function:
function asyncFunc(i) {
setTimeout(function () {
console.log(i);
}, 1000);
}
if I want to execute this asyncFunc 5 times in a for loop, i.e. log 1 - 5 per second, and totally costs 5 seconds.
1
2
3
4
5
I know jQuery's when().done() can do that however if I am in a environment with NO 3rd party JS libraries, what is the simplest and elegant way to achieve this?
Actually for example I want to write a util function which accepts an array of async functions, and this util function can execute passed in functions one by one:
function execAsyncTasks([asyncTask1, asyncTask2, asyncTask3]) {
asyncTask1();
// Wait until asyncTask1 finished
asyncTask2();
// Wait until asyncTask2 finished
asyncTask3();
// Wait until asyncTask3 finished
}
All your tasks will have to implement some sort of callback mechanism, because that's the only way you'll ever know that an asynchronous task has been completed. Having that, you could do something like:
function executeTasks() {
var tasks = Array.prototype.concat.apply([], arguments);
var task = tasks.shift();
task(function() {
if(tasks.length > 0)
executeTasks.apply(this, tasks);
});
}
executeTasks(t1, t2, t3, t4);
Demo
You can use Async module:
https://github.com/caolan/async
async.parallel([
function(){ ... },
function(){ ... }
], callback);
async.series([
function(){ ... },
function(){ ... }
]);
This is one approach of many
function execAsyncTasks(asyncTask1, asyncTask2, asyncTask3) {
var count = 0;
function nextCommand() {
switch (count) {
case 0:
asyncTask1();
break;
case 1:
asyncTask2();
break;
case 2:
asyncTask3();
default:
return;
}
count++;
setTimeout(nextCommand, 1000);
}
nextCommand();
}
you can have a sync mechanism using callbacks and recursive function calls: see http://jsfiddle.net
function asyncFunc(i, callback) {
setTimeout(function() {
document.body.innerHTML += '<p>' + i + '</p>';
callback();
}, 1000);
}
var args = [0, 1, 2, 3, 4];
function loopThroughArgs(callback) {
if (args.length == 0) {
callback();
} else {
asyncFunc(args[0], function() {
args.splice(0, 1); //remove the first item from args array
loopThroughArgs(callback);
});
}
}
loopThroughArgs(function() {
document.body.innerHTML += '<p>done !</p>';
});
Related
i have problem to create deep number of callback function in javascript dynamically. For example i have function like this.
function process(value, callback) {
console.log('process ' + value)
callback()
}
function complete() {
console.log('complete')
}
function running(count){
// number process function is two
if (count==2) {
process('number one', function () {
process('number two', function () {
complete() => // last callback is closed by complete function
})
})
}
// number process function is three
if (count==3) {
process('number one', function () {
process('number two', function () {
process('number three', function () {
complete() => // last callback is closed by complete function
})
})
})
}
}
running(3);
Output :
process number one
process number two
process number three
completed
i want to create number callback is dynamic and closed by complete function, not using if/switch command, how to do that? thank you
You could use recursion and that will exit and run complete when the count param is zero otherwise it will call process function.
function process(value, callback) {
console.log('process ' + value)
callback()
}
function complete() {
console.log('complete')
}
const p = ['three', 'two', 'one']
function running(count) {
if (count) {
process(`number ${p[count - 1]}`, () => {
running(count - 1)
})
} else {
complete()
}
}
running(3);
You can do without using callback in this case:
var processNames = ['one', 'two', 'three'];
function process(value) {
console.log('process ' + value);
}
function complete() {
console.log('complete');
}
function running(count){
for (var index = 0; index < count; index++) {
var name = 'number ' + processNames[index];
process(name);
}
complete();
}
running(3);
You could use promises for this.
I create the three promises using a for loop and put them in an array. The resolve functions write the index to the console. Use Promise.all to execute them in order and use finally to write completed.
With the promise we don't need to provide a callback function.
function process(value) {
console.log('process ' + value)
}
function complete() {
console.log('complete')
}
const textInt = ['one', 'two', 'three']
function running(count){
const promiseArray = [];
for (let i = 0; i < count; i++)
{
promiseArray[new Promise(function(){
process(textInt[i], function(){});
})];
}
Promise.all(promiseArray).finally(complete)
}
running(3);
In the example below I have a function that calls another function (which in reality may call a further function or make an Ajax request).
The example works for deferring the first function but I have no idea how to make it resolve other functions that it may call.
Do I have to pass these deferred objects around to the other functions, or is there a more elegant way around this? (In reality, I'm dealing with speech synthesis using the API callbacks so the basic structure in the example can't be changed so much).
Fiddle here
https://jsfiddle.net/macgroover/ahz46rw1/
function slowCount(numbers, deferred) {
if (deferred) {
this.deferred = jQuery.Deferred();
}
if (numbers.length) {
var number = numbers.shift();
log('SC:' + number);
setTimeout(function() {
doSomething(number);
slowCount(numbers);
}, 500);
return this.deferred.promise();
} else {
this.deferred.resolveWith(this, ['resolveWith']);
//this.deferred.resolve();
return;
}
}
function doSomething(number) {
setTimeout(function() {
log("DS:" + number);
}, 1000);
}
$(function() {
$.when(slowCount([1, 2, 3, 4], true)).done(function(rslt) {
log("All tasks finished with " + rslt);
});
});
Have a look at these rules - especially, always promisify at the lowest level, which is setTimeout for you:
function wait(timeout) {
var deferred = jQuery.Deferred();
setTimeout(deferred.resolve, timeout);
return deferred.promise();
}
Now the rest is fairly trivial:
function slowCount(numbers) {
if (numbers.length) {
var number = numbers.shift();
log('SC:' + number);
return wait(500).then(function() {
return doSomething(number);
}).then(function() {
return slowCount(numbers);
});
} else {
return $.when("end result");
}
}
function doSomething(number) {
// I assume you want this to be asynchronous as well
// - so it returns a promise!
return wait(1000).then(function() {
log("DS:" + number);
});
}
$(function() {
slowCount([1, 2, 3, 4]).then(function(rslt) {
log("All tasks finished with " + rslt);
});
});
I'm trying to apply what I learned about callback functions in this post I made to extend to 3 functions, but am having some trouble getting things working. Can someone please help me understand how I can get these three functions to fire in sequence?
var yourCallback = function(args, second) {
var t = setTimeout(function() {
$('body').append(args);
}, 800);
second('3-');
}
var yourSecondCallback = function(args) {
var t = setTimeout(function() {
$('body').append(args);
}, 800);
}
function function1(args, callback, yourSecondCallback) {
$('body').append(args);
if (callback) {
callback('2-');
}
}
function1('1-' , yourCallback);
http://jsfiddle.net/loren_hibbard/WfKx2/3/
Thank you very much!
You need to nest the callbacks to get them to call in order.
var yourCallback = function(args, second) {
var t = setTimeout(function() {
$('body').append(args);
second('3-');
}, 800);
}
var yourSecondCallback = function(args) {
var t = setTimeout(function() {
$('body').append(args);
}, 800);
}
function function1(args, callback) {
$('body').append(args);
if (callback) {
callback('2-', yourSecondCallback);
}
}
function1('1-' , yourCallback);
Here's your altered fiddle
Your function names confuse me, so I'm just going to make some up to demonstrate a simple approach:
function1('-1', function(){
secondCallback(...);
thirdCallback(...);
...
});
Any reason a simple approach like that won't work for you?
Not sure exactly what you are trying to do here, but when you do this in function1:
callback('2-');
You are calling this method:
var yourCallback = function(args, second)
But you are not providing a value for second, so you get an error.
If your first argument and only is going to be an input for all the callbacks then this code can be used for unlimited arguments
var yourCallback = function(args, second) {
var t = setTimeout(function() {
$('body').append(args + ' first function');
}, 800);
}
var yourSecondCallback = function(args) {
var t = setTimeout(function() {
$('body').append(args + ' second function');
}, 800);
}
function function1(args) {
var callbacks = arguments.length - 1;
for (i = 1; i < arguments.length; i++) {
if (typeof(arguments[i] == 'function')) {
arguments[i](arguments[0]);
}
}
}
function1('1-', yourCallback, yourSecondCallback);
Fiddle - http://jsfiddle.net/8squF/
I have a function, mainMethod, that is calling three callback functions.
mainFunction the first callback function(one) will be called and the first parameter will be passed into it.
one will pass the second parameter into the second callback function (two).
two will pass the third parameter into the last callback function (three).
three will just log the last parameter that was passed into it.
function mainFunction(callback1, callback2, callback3){
var first_parameter = "ONE"
callback1(first_parameter);
}
function one(a){
console.log("one: " + a);
var second_parameter = "TWO"
two(second_parameter);
}
function two(b){
console.log("two: " + b);
var third_parameter = "THREE";
three(third_parameter);
}
function three(c){
console.log("three: " + c);
}
mainFunction(one, two, three);
Check out this code :
Link
<span>Moving</span>
$('#link').click(function () {
console.log("Enter");
$('#link').animate({ width: 200 }, 2000, function() {
console.log("finished");
});
console.log("Exit");
});
As you can see in the console, the "animate" function is asynchronous, and it "fork"s the flow of the event handler block code. In fact :
$('#link').click(function () {
console.log("Enter");
asyncFunct();
console.log("Exit");
});
function asyncFunct() {
console.log("finished");
}
follow the flow of the block code!
If I wish to create my function asyncFunct() { } with this behaviour, how can I do it with javascript/jquery? I think there is a strategy without the use of setTimeout()
You cannot make a truly custom asynchronous function. You'll eventually have to leverage on a technology provided natively, such as:
setInterval
setTimeout
requestAnimationFrame
XMLHttpRequest
WebSocket
Worker
Some HTML5 APIs such as the File API, Web Database API
Technologies that support onload
... many others
In fact, for the animation jQuery uses setInterval.
You can use a timer:
setTimeout( yourFn, 0 );
(where yourFn is a reference to your function)
or, with Lodash:
_.defer( yourFn );
Defers invoking the func until the current call stack has cleared. Any additional arguments are provided to func when it's invoked.
here you have simple solution (other write about it)
http://www.benlesh.com/2012/05/calling-javascript-function.html
And here you have above ready solution:
function async(your_function, callback) {
setTimeout(function() {
your_function();
if (callback) {callback();}
}, 0);
}
TEST 1 (may output '1 x 2 3' or '1 2 x 3' or '1 2 3 x'):
console.log(1);
async(function() {console.log('x')}, null);
console.log(2);
console.log(3);
TEST 2 (will always output 'x 1'):
async(function() {console.log('x');}, function() {console.log(1);});
This function is executed with timeout 0 - it will simulate asynchronous task
Here is a function that takes in another function and outputs a version that runs async.
var async = function (func) {
return function () {
var args = arguments;
setTimeout(function () {
func.apply(this, args);
}, 0);
};
};
It is used as a simple way to make an async function:
var anyncFunction = async(function (callback) {
doSomething();
callback();
});
This is different from #fider's answer because the function itself has its own structure (no callback added on, it's already in the function) and also because it creates a new function that can be used.
Edit: I totally misunderstood the question. In the browser, I would use setTimeout. If it was important that it ran in another thread, I would use Web Workers.
Late, but to show an easy solution using promises after their introduction in ES6, it handles asynchronous calls a lot easier:
You set the asynchronous code in a new promise:
var asyncFunct = new Promise(function(resolve, reject) {
$('#link').animate({ width: 200 }, 2000, function() {
console.log("finished");
resolve();
});
});
Note to set resolve() when async call finishes.
Then you add the code that you want to run after async call finishes inside .then() of the promise:
asyncFunct.then((result) => {
console.log("Exit");
});
Here is a snippet of it:
$('#link').click(function () {
console.log("Enter");
var asyncFunct = new Promise(function(resolve, reject) {
$('#link').animate({ width: 200 }, 2000, function() {
console.log("finished");
resolve();
});
});
asyncFunct.then((result) => {
console.log("Exit");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Link
<span>Moving</span>
or JSFiddle
This page walks you through the basics of creating an async javascript function.
Since ES2017, asynchronous javacript functions are much easier to write. You should also read more on Promises.
If you want to use Parameters and regulate the maximum number of async functions you can use a simple async worker I've build:
var BackgroundWorker = function(maxTasks) {
this.maxTasks = maxTasks || 100;
this.runningTasks = 0;
this.taskQueue = [];
};
/* runs an async task */
BackgroundWorker.prototype.runTask = function(task, delay, params) {
var self = this;
if(self.runningTasks >= self.maxTasks) {
self.taskQueue.push({ task: task, delay: delay, params: params});
} else {
self.runningTasks += 1;
var runnable = function(params) {
try {
task(params);
} catch(err) {
console.log(err);
}
self.taskCompleted();
}
// this approach uses current standards:
setTimeout(runnable, delay, params);
}
}
BackgroundWorker.prototype.taskCompleted = function() {
this.runningTasks -= 1;
// are any tasks waiting in queue?
if(this.taskQueue.length > 0) {
// it seems so! let's run it x)
var taskInfo = this.taskQueue.splice(0, 1)[0];
this.runTask(taskInfo.task, taskInfo.delay, taskInfo.params);
}
}
You can use it like this:
var myFunction = function() {
...
}
var myFunctionB = function() {
...
}
var myParams = { name: "John" };
var bgworker = new BackgroundWorker();
bgworker.runTask(myFunction, 0, myParams);
bgworker.runTask(myFunctionB, 0, null);
Function.prototype.applyAsync = function(params, cb){
var function_context = this;
setTimeout(function(){
var val = function_context.apply(undefined, params);
if(cb) cb(val);
}, 0);
}
// usage
var double = function(n){return 2*n;};
var display = function(){console.log(arguments); return undefined;};
double.applyAsync([3], display);
Although not fundamentally different than the other solutions, I think my solution does a few additional nice things:
it allows for parameters to the functions
it passes the output of the function to the callback
it is added to Function.prototype allowing a nicer way to call it
Also, the similarity to the built-in function Function.prototype.apply seems appropriate to me.
Next to the great answer by #pimvdb, and just in case you where wondering, async.js does not offer truly asynchronous functions either. Here is a (very) stripped down version of the library's main method:
function asyncify(func) { // signature: func(array)
return function (array, callback) {
var result;
try {
result = func.apply(this, array);
} catch (e) {
return callback(e);
}
/* code ommited in case func returns a promise */
callback(null, result);
};
}
So the function protects from errors and gracefully hands it to the callback to handle, but the code is as synchronous as any other JS function.
Unfortunately, JavaScript doesn't provide an async functionality. It works only in a single one thread. But the most of the modern browsers provide Workers, that are second scripts which gets executed in background and can return a result.
So, I reached a solution I think it's useful to asynchronously run a function, which creates a worker for each async call.
The code below contains the function async to call in background.
Function.prototype.async = function(callback) {
let blob = new Blob([ "self.addEventListener('message', function(e) { self.postMessage({ result: (" + this + ").apply(null, e.data) }); }, false);" ], { type: "text/javascript" });
let worker = new Worker(window.URL.createObjectURL(blob));
worker.addEventListener("message", function(e) {
this(e.data.result);
}.bind(callback), false);
return function() {
this.postMessage(Array.from(arguments));
}.bind(worker);
};
This is an example for usage:
(function(x) {
for (let i = 0; i < 999999999; i++) {}
return x * 2;
}).async(function(result) {
alert(result);
})(10);
This executes a function which iterate a for with a huge number to take time as demonstration of asynchronicity, and then gets the double of the passed number.
The async method provides a function which calls the wanted function in background, and in that which is provided as parameter of async callbacks the return in its unique parameter.
So in the callback function I alert the result.
MDN has a good example on the use of setTimeout preserving "this".
Like the following:
function doSomething() {
// use 'this' to handle the selected element here
}
$(".someSelector").each(function() {
setTimeout(doSomething.bind(this), 0);
});
I have a recursive function which does a sort of tree process where each call may call itself multiple times, I don't have any way of knowing how deep or wide it is. How do I run a callback once the entire process has been completed?
I'm thinking of having some sort of object to pass about to do a count but not quite cracked it yet, i'm wondering if there is a known best/better way of doing this.
You could do something like:
function recurseTree(arg, callback) {
var recurse = function(a) {
if (someCondition) {
recurse(a);
}
};
recurse(arg);
callback();
}
All of your actual recursive logic will go in the recurse function, and the callback will be called only after all recursion is finished.
EDIT:
Here is a simple implementation
function recursiveAlert(x, callback) {
var recurse = function(y) {
alert(y);
if (y < 3) {
recurse(y + 1);
}
}
recurse(x);
callback();
}
recursiveAlert(0, function() { alert('done'); });
what I needed to do is count the number of paths in each tree before calling the callback e.g.:
myFunction: function(tree) {
var count = 0;
finishCallback = function() {
if (--count === 0){
callback();
};
};
recursion = function(subTree) {
count = tree.paths.length;
_.each(subTree.path, function(route) {
count += subFolder.fileRefs.length;
recursion(route, function() {
finishCallback();
});
});
};
recursion(tree);
}
Perhaps the count should not be inside myFunction but recursion should have its own count, however this works. (i've not tested this example)