Chris
Chris

Reputation: 7288

What is this timeout-related feature of javascript called?

I'm familiar with this behavior, but don't have the vocabulary to describe (and thus google) it.

setTimeout(function () { alert("timeout!"); }, 1000);
veryLongProcess();  // lasts longer than 1000 milliseconds

I believe the result of this is that you get your alert after the long process is finished, i.e. longer than 1 second after the code was executed. I imagine this as timeouts sending functions to some separate "thread" or "stack" or "cycle" that can only start after the current one is finished, even if that current one takes longer than the timeout was originally specified for.

Is there a name for this? How can I learn more about how it works?

Upvotes: 0

Views: 46

Answers (2)

ejc
ejc

Reputation: 343

What you're looking for is called "callback functions." You can pass functions as a variables to other functions, and then execute them whenever you want. I wrote a quick sample for how it works below (untested).

function longProcess(callback){
    //a bunch of code execution goes here
    var testNumber = 5;

    //This portion of code happens after all desired code is run
    if (callback != undefined){  //Check to see if a variable 'callback' was passed... we're assuming it's a function
        callback(testNumber);    //Execute the callback, passing it a value
    }
}

function testCallback(number){
    alert("Number: " + number);  //Alert box will popup with "Number: 5"
}

longProcess(testCallback);       //Call your long process, passing another function as a variable

Upvotes: 0

Bryce
Bryce

Reputation: 6630

I believe you may be looking for the term 'synchronous' programming.

Since JavaScript is single threaded, your veryLongProcess() will in fact cause the alert to trigger after 1000ms because of something called blocking.

Be aware that blocking JavaScript can degrade the user experience significantly, such as locking up the browser, or causing it to show a 'kill script' dialog, breaking the functionality of your process.

Upvotes: 2

Related Questions