前端面试题之setTimeout()
1 <script type="text/javascript"> 2 var t=true; 3 window.setTimeout(function(){ 4 t=false; 5 },1000); 6 while(t){ 7 } 8 alert('end'); 9 </script>
注:setTimeout(code,millisec)方法的意思是:在指定的毫秒数后调用函数或计算表达式。
这是一道前端面试题。考点在于“JS是单线程运行的语言”。这将会是一个死循环。
<script type="text/javascript"> var t=true; // 声明 t 为 true window.setTimeout(function(){ t=false; },1000); // 1秒后设置 t 为 false while(t){ } // 开始死循环,这是 t 为 true // ... // 本以为1秒后会设置为false的t,根本没有机会再执行了。 alert('end'); </script>
浙公网安备 33010602011771号