Is JavaScript single threaded? If not, how do I get synchronized access to shared data?

前端 未结 7 1920
执笔经年
执笔经年 2020-12-17 01:12

I have a web page with DIVs with a mouseover handler that is intended to show a pop-up information bubble. I don\'t want more than one info bubble

相关标签:
7条回答
  • 2020-12-17 01:51

    Here's the working version, more or less. When creating items we attach a mouseover event:

    var self = this;
    SimileAjax.DOM.registerEvent(labelElmtData.elmt, "mouseover", function (elt, domEvt, target) {
        return self._onHover(labelElmtData.elmt, domEvt, evt);
    });
    

    This calls a function that sets a timeout (pre-existing timeouts for a different item is cancelled first):

    MyPlan.EventPainter.prototype._onHover = function(target, domEvt, evt) {            
        ... calculate x and y ...
        domEvt.cancelBubble = true;
        SimileAjax.DOM.cancelEvent(domEvt);
        this._futureShowBubble(x, y, evt);
    
        return false;
    }
    MyPlan.EventPainter.prototype._futureShowBubble = function (x, y, evt) {
        if (this._futurePopup) {
            if (evt.getID() == this._futurePopup.evt.getID()) {
                return;
            } else {
                /* We had queued a different event's pop-up; this must now be cancelled. */
                window.clearTimeout(this._futurePopup.timeoutID);
            } 
        }
        this._futurePopup = {
            x: x,
            y: y,
            evt: evt
        };    
        var self = this;
        this._futurePopup.timeoutID =  window.setTimeout(function () {
                self._onTimeout();
        }, this._popupTimeout);
    }
    

    This in turn shows the bubble if it fires before being cancelled:

    MyPlan.EventPainter.prototype._onTimeout = function () {
        this._showBubble(this._futurePopup.x, this._futurePopup.y, this._futurePopup.evt);
    
    };
    
    MyPlan.EventPainter.prototype._showBubble = function(x, y, evt) {
        if (this._futurePopup) {
            window.clearTimeout(this._futurePopup.timeoutID);
            this._futurePopup = null;
        }        
        ...
    
        SimileAjax.WindowManager.cancelPopups();
        SimileAjax.Graphics.createBubbleForContentAndPoint(...);
    };
    

    This seems to work now I have set the timeout to 200 ms rather than 100 ms. Not sure why too short a timeout causes the multi-bubble thing to happen, but I guess queuing of window events or something might still be happening while the newly added elements are being laid out.

    0 讨论(0)
提交回复
热议问题