javascript让ui线程让出时间片的模型

时间:2022-01-15 02:05:13
<html>
    <head>
        <script type="text/javascript">

             function   sleep(n) 
            { 
                 var   start= new   Date().getTime(); 
                 while( true)    if( new   Date().getTime()-start> n)    break;                 
            } 

             function handleClick(abc)
            {
                 var div;                
                    div=document.createElement("span");
                    div.innerHTML=abc+"";                            
                    document.body.appendChild(div);    

                                                
            }
            
             function processArray(items,process,callback)
            {                            
                 var todo=items.concat(); // 克隆数组

                setTimeout( function(){
                     var item=todo.shift();
                    process(item);
                    
                     if(todo.length>0)                     
                    {        
                         // alert(arguments.callee.toString());
                        setTimeout(arguments.callee,25);//递归调用等同于下面的一句
                         // processArray(todo,process,callback);
                    }
                     else
                    {
                        callback(items);
                    }
                },25)
            }

             function test()
            {
                 var items1=[123,234,345,456,567,678,789,890,123,234,345,456,567,678,789,890,123,234,345,456,567,678,789,890,123,234,345,456,567,678,789,890,123,234,345,456,567,678,789,890,123,234,345,456,567,678,789,890,123,234,345,456,567,678,789,890,123,234,345,456,567,678,789,890,123,234,345,456,567,678,789,890,123,234,345,456,567,678,789,890,123,234,345,456,567,678,789,890];
                
                processArray(items1,handleClick, function(){handleClick("done");})
            }            
           
        </script>    
    </head>
    <body>
        <input type="button" onclick="test()" value="Cliek Me"/>                
        <select type="select">
            <option value='1'>1</option>
            <option value='2'>2</option>
            <option value='3'>3</option>
            <option value='4'>4</option>
            <option value='5'>5</option>
        </input>
    </body>
</html>