Can JavaScript function execution be interrupted?

前端 未结 3 1296
天命终不由人
天命终不由人 2020-12-10 08:58

Having an object to store data.

var store = {
    elements: [],
    eventsEnabled: true,
    addElement: function(element) {
        this.elements.push(eleme         


        
相关标签:
3条回答
  • 2020-12-10 09:12

    Would it not be more sensible to pass the eventsEnabled in as a parameter to the addElement method?

    var store = {
        elements: [],
        addElement: function(element,eventsEnabled) {
            this.elements.push(element);
            if (eventsEnabled) {
                // Code that triggers event, calls handlers... whatever
            }
        }
    };
    

    First:

    setInterval(function() {
        store.addElement('hello',false);
    }, 12000);
    

    Second:

    setInterval(function() {
        store.addElement('bye',true);
    }, 12000);
    
    0 讨论(0)
  • 2020-12-10 09:14

    Further to @Jamiec's suggestion, you could also look at passing the event function in as well:

    var store = {
        elements: [],
        addElement: function(element, callback) {
            this.elements.push(element);
            if (callback !== undefined) {
                callback();
                // Common code that triggers event, calls handlers... whatever
                alert("I'm Common Event Code");
            }
        }
    };​
    

    Used as such:

    setInterval(function() {
        store.addElement('hello', function(){ alert("I'm Special Event Code!"); });
    }, 12000);
    

    Thus, if an event is needed, you can pass it in, else just leave it out.

    0 讨论(0)
  • 2020-12-10 09:16

    JavaScript is single-threaded. A function cannot be interrupted, so you can be sure each function block will complete before another begins.

    (However, if a function makes an asynchronous call, other functions may execute before the asynchronous operation starts. That doesn't happen in your code, though, that I can see, besides the setTimeout calls, and you can be sure those will execute in the correct order.)

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