js achieve sleep sleep [Bo]

First js native does not support sleep, all current programs are indirect implementation.
Requirements:

for (i=0;i<100;i++){
    echartsPlots(xxx[i]);
}

Inside is where echartsPlots ajax call back directly perform background is extremely easy to get stuck inside the data query and processing are slower. I hope after echartsPlots execution, sleep for some time, and then the cycle continues a task. Under execution
method, cycle achieve

function sleep(delay) {
    for (var t = Date.now(); Date.now() - t <= delay;) ;
}

The easiest method most pit father of
the reason that pit father, mainly because of the effect, and indeed achieve the purpose of sleep, but the actual cost of client-side at the expense of efficiency, after all cpu at idle.
So, I can achieve the desired effect?

for (i=0;i<100;i++){
    echartsPlots(xxx[i]);
    sleep(1000)//毫秒
}

Actually it is not (ajax requests are stuck in pending state, the actual back-end has been returned), because they want to please the next prompt (js nature of single-threaded)

Method 2, setTimeout (with the setInterval)

function loop(i) {
    console.log(i);
    i++;
    if (i<10)
        setTimeout(function () {
            loop(i);
        }, 2000);
}
loop(0);

This is a recursive achieve similar effect on demand to achieve? Yes, this is no problem

Add that on setTimeout and setInterval
recommended setInterval
refer to this article: setInterval () and setTimeout () difference .https: //blog.csdn.net/mayue24/article/details/80879685

Published 238 original articles · won praise 144 · views 860 000 +

Guess you like

Origin blog.csdn.net/u011331731/article/details/103838201