Does javascript have a sort of event listeners? 开发者_高级运维
My scenario:
I want to execute Inc function 2 times with different parameters, first execution of Inc and then the second execution, but the second execution must be executed after X seconds (settimeout...) after the first Inc function is completed (all it's iterations, as soon as clearInterval ).So I need sort of event and a listener (of-course it must be asynchronous).
What can you suggest? (please no jquery...)function Inc(val1,val2){
var intervalID = setInterval(function(){
if (val1 > val2) clearInterval(intervalID);
val1= val1 + 10;
}, 400);
}
I usually try to stay away from timeouts, especially if they deal with something that requires recursion.
But why do you need recursion if the function is only executed twice?
// call Inc the first time
Inc();
// this will execute only after the first Inc(); is done.
// call Inc the second time after X seconds
setTimeout(Inc, 400);
Edit: Well, since I don't know why you don't want it to know about the continuation, here's another suggestion with the exact same semantics but maybe a desirable syntax, now there is a simulation of event delegation anyway :) (thing is, you need the Inc function to somehow report completion):
function Inc(val1,val2){
var handle = { oncomplete: null };
var intervalID = setInterval(function(){
if (val1 > val2)
{
clearInterval(intervalID);
if (handle.oncomplete) handle.oncomplete();
}
val1 = val1 + 10;
}, 400);
return handle;
}
Inc(10, 40).oncomplete = function(){ alert("Finish"); };
Previous: Something like this should to the trick (I did not test it though):
function Inc(val1,val2, continuation){
var intervalID = setInterval(function(){
if (val1 > val2)
{
clearInterval(intervalID);
if (continuation) continuation();
}
val1 = val1 + 10;
}, 400); }
Then call it like this:
Inc(x, y, function(){ Inc(y, z); });
AFAIK there is no type of standarized custom-eventing, but you are making the work-around.
Calling a "delegate" this way:
var myFunction = function() {
// CALL Inc with different params, this is your "event"
};
function Inc(val1, val2) {
setInterval(myFunction,400);
}
Short answer, not for custom events (only DOM-standard events), but you can fake it.
精彩评论