A small pit in the SetTimeout method

Source: Internet
Author: User

Thoreau said: "I go to the forest, because I hope to live hard, only to face the purest truth of life, to see if I understand its true meaning, to avoid the time of death, only to find that they have not lived at all ..."

Thoreau is not a program ape, but Thoreau to the program Ape is also a revelation: some pits, only you jump into the desperate, you will profound the truth of those codes, otherwise to the death, only to find that they have not written any decent procedures.

Since the touch of Nodejs, it is natural to be abused by multiple nested callback functions. It is said that Commonjs gave a specification called promise, then many JS libraries have introduced a promise programming model to facilitate the writing of asynchronous calling code. For the Beginner's program apes, these abstract patterns are the easiest to comprehend. Of course, stupid people naturally have a stupid way, as Forrest Gump said: Stupid is as stupid does. Stupid people do stupid things--to the web search on the simplest case code, a little knock out, around Console.log. Then, there are a lot of pits, and these pits may not be from the current new thing, but they have some basic knowledge is not solid.

function Asyncfunction () {return 

            new Promise (function (resolve, reject) {        

                settimeout (function () {            

                    Resolve (' Async Hello World ')



;} Asyncfunction (). Then (function (value) {

    console.log (value);    => ' Async Hello World '

}. catch (function (error) {

    console.log (error);

});

The above code is copied directly from a website, run a bit, at first sight did not find any pits. However, when I changed the code, I created a pit for myself.

var q=require (' Q ');

var start= (new Date ()). GetTime ();

var asyncp=function () {return

    new Promise (function (resolve,reject) {

        settimeout (resolve);

        Console.log (' start at ' +start)

    }

}



function onfullfilled (v) {

    console.log ('--' +v ');

    Console.log (' Now's time span ' + (new Date ()). GetTime ()-start));

    return v+10;

}



ASYNCP (). Then (onfullfilled). Then (onfullfilled). then (onfullfilled);

The result of the execution is this:

OK 500 milliseconds to execute the sentence "settimeout (Resolve (34), 500);" How did it not come into effect. Look at the results printed: The time span is xxxxx, none of which is more than 500 milliseconds. This shows that there is a big problem with this asynchronous execution. Similar problems I have encountered before, so far did not find a suitable explanation, but the self summed up as: SetTimeout (func, TimeSpan) This method, func if writing a function name can not take parameters, if you need to take parameters, you can only write an anonymous function, It then writes the referenced functions and parameters in the body of the function, otherwise the referenced function does not wait for the timespan to execute, but executes immediately. The following comparison code shows the difference.

Chestnut A:

var start= (new Date ()). GetTime ();

Console.log (' start at ' +start)

settimeout (Test (3), 1000);

function Test (v) {

    console.log (' test ');

    Console.log (' Now's time span is ' + ((new Date ()). GetTime ()-start));

}

The results of the execution are:

Chestnut B:

var start= (new Date ()). GetTime ();

Console.log (' start at ' +start)

settimeout (test,1000);

function test () {

    console.log (' test ');

    Console.log (' Now's time span is ' + ((new Date ()). GetTime ()-start));

}

The results of the execution are:

The only difference between chestnuts A and chestnut B is settimeout when one writes test and one writes test (3). At this point, I suddenly understand that the first parameter, as defined by the SetTimeout method, is the function, not the result of the function execution. So the first argument that settimeout gets in chestnut A is actually undefined--because the test method's execution result doesn't return anything.

So, this is a pit that almost made me think the simple implementation code of the promise that I found before is not available. writing is a great advantage, whether you write code or text. Even if you write to yourself, you will let yourself see something different .

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.