user3029571
user3029571

Reputation: 31

JavaScript variables "out of focus"?

I have a function (see below) that writes a message out onto the screen. Whenever you're actively viewing the page that it is running on, it prints out just fine; however, say you're watching a video in another tab and switch back to the tab that is writing out the function, the text comes out all jumble. e.g: "This is a message." generally would come out scrambled like "t isa hismg esseg."

The function in question:

params:

message: string

object: an HTML Object

function writeMessage(message,object){
    var i = 0;
    var interval = setInterval(function(){
        if(i < message.length){
            object.append(message.substr(i,1));
            i++;
        }else{
            clearInterval(interval);
        }
    }, 25);
}

Any idea as to why this happens?

Upvotes: 0

Views: 90

Answers (1)

Honza Brestan
Honza Brestan

Reputation: 10957

I haven't tested that, but if what the comments say is true, you should be able to avoid that by manually chaining individual delayed operations. Instead of defining one interval, you should be able to call one timeout (setTimeout function), that appends the letter to the object and then calls itself recursively while passing the rest of the message to the recursive call.

In this case, if the device gives your asynchronous action no processor time, at least the subsequent actions won't be created and executed - because only the code in the first (now waiting) action could do that.

Alternatively you can use Reactive Extensions to generate an observable interval, upon which you can subscribe and update the object with your message. If you're not familiar with reactive programming, it might be a huge new topic for you, but I can certainly recommend it - if only just as a brain-teaser to see a different approach to programming.

Upvotes: 2

Related Questions