为什么代码会跳过 setTimeout 并且稍后才赶上?

编程入门 行业动态 更新时间:2024-10-24 22:26:09
本文介绍了为什么代码会跳过 setTimeout 并且稍后才赶上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

目标是在容器边界内的随机位置创建一个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 并且稍后才赶上?

本文发布于:2023-11-26 17:45:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634559.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:跳过   稍后   代码   setTimeout

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!