Kayote
Kayote

Reputation: 15647

Pause function while another function finishes

Im struggling with this code:

Within 'swapFunc' function, I append an addEventListener to 'tEleBaby' element, immediately after which, I trigger the addEventListener by replacing the class of 'tEleBaby'.

The problem is with the code within 'setTimeout', which needs to run after the 'animListener' function has completed. Im not keen on using setTimeout so would prefer a more sensible / correct way of dealing with this.

swapFunc: function swapFunc(tEle, swapEle) {
    var tEle = document.getElementById(tEle);
    var tEleBaby = tEle.children[0];
    tEleBaby.addEventListener("animationend", this.animListener, false);
    tEleBaby.classList.add("animFadeOut");
    // I want to remove the setTimeout; i.e. the animListener func should feedback to swapFunc
    setTimeout(function () {
        tEle.id = swapEle;
        tEle.setAttribute("data-action", dataAction);
        tEle.setAttribute("data-tooltip", dataTooltip);
    }, 500);
},

animListener: function animListener(ev) {
    if (ev.type.toLowerCase().indexOf("animationend") >= 0) {
        var eventTarget = ev.target;
        eventTarget.className = "animFadeIn cFBIcons";
    }
},

Upvotes: 0

Views: 73

Answers (2)

plalx
plalx

Reputation: 43728

Why don't you simply put that code in the event handler?

var self = this;

tEleBaby.addEventListener ("animationend" , function (ev) {
    self.animListener(ev);
    //rest of code
} , false);

Upvotes: 1

loxxy
loxxy

Reputation: 13151

Try it this way :

swapFunc: function swapFunc(tEle, swapEle) {
    var tEle = document.getElementById(tEle);
    var tEleBaby = tEle.children[0];
    tEleBaby.addEventListener("animationend", listener, false);
    tEleBaby.classList.add("animFadeOut");

    function listener(ev) {
        animListener(ev, callMe);
    }

    function callMe() {
        tEle.id = swapEle;
        tEle.setAttribute("data-action", dataAction);
        tEle.setAttribute("data-tooltip", dataTooltip);
    }
},

animListener: function animListener(ev, callback) {
    if (ev.type.toLowerCase().indexOf("animationend") >= 0) {
        var eventTarget = ev.target;
        eventTarget.className = "animFadeIn cFBIcons";
    }
    callback();
},

Upvotes: 1

Related Questions