为什么代码会跳过 setTimeout 并且稍后才赶上? [英] Why does the code skip the setTimeout and only later catch up?

查看:56
本文介绍了为什么代码会跳过 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.

参考:https://developer.mozilla.org/en/docs/Web/JavaScript/EventLoop

这篇关于为什么代码会跳过 setTimeout 并且稍后才赶上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆