目标是在容器边界内的随机位置创建一个div,等待3秒然后销毁该div;冲洗并重复 3 次.然而,据我所知,结果是当 setTimeout 等待三秒时,代码继续循环",并且只有在 3 秒后才会执行 setTimeout 中的函数.我不小心创建了两个线程?
The goal is to create a div in a random location within the bounds of the container, wait 3 seconds then destroy the div; rinse and repeat 3 times. The outcome however, from what I can tell, is that while the setTimeout waits the three seconds, the code continues the 'loop' and only after the 3 seconds does the function inside the setTimeout executes. Did I accidentally create two threads?
$(document).ready(function() { var $bug = "<div class='bug'><div>"; var x = 0; var timer = setInterval(function() { if (x > 3) { clearInterval(timer); } r1 = Math.floor((Math.random() * 270) + 1); r2 = Math.floor((Math.random() * 270) + 1); $('#container').append("<div class='bug'style='top:" + r1 + "px;left:" + r2 + "px;'></div>") x++; setTimeout(function() { $('.bug').remove(); }, 3000) }, 1000); }); 推荐答案我相信这与事件循环以及 javascript setTimeout 函数本质上是非阻塞函数并被称为异步这一事实有关.
I believe it has got something to do with event loops and the fact that javascript setTimeout function is non-blocking in nature and is called asynchronous.
参考:developer.mozilla/en/docs/Web/JavaScript/EventLoop
更多推荐
为什么代码会跳过 setTimeout 并且稍后才赶上?
发布评论