luppi
luppi

Reputation: 301

Event listeners in JavaScript

Does JavaScript have a sort of event listeners?

My scenario:
I want to execute Inc function twice 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);
                
}

Upvotes: 1

Views: 792

Answers (3)

Ekin Koc
Ekin Koc

Reputation: 2997

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); });

Upvotes: 1

Luca Matteis
Luca Matteis

Reputation: 29267

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);

Upvotes: 2

jpabluz
jpabluz

Reputation: 1312

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.

Upvotes: 0

Related Questions