简体   繁体   English

Settimeout() 不等待。 为什么?

[英]Settimeout() doesn't wait. Why?

In upper part, both settimeout s inside "if" work properly.在上半部分,“if”中的两个settimeout都正常工作。 However settimeout s in lower part, the ones inside "else" does not wait.然而settimeout在下部,“else”里面的那些不等待。 As far as I can see, I've written them in exact same style in both parts.据我所知,我在两个部分都以完全相同的风格编写它们。 What could be the reason ?可能是什么原因 ?

    elementCopy.addEventListener('mouseleave',()=>{
                    elementCopy.classList.add('leavin');
                    setTimeout(() => {                                         //  THESE WORK PROPERLY
                        elementCopy.style.width = '36vw';
                        setTimeout(() => {
                            elementCopy.parentElement.removeChild(elementCopy);
                        }, 400);         
                    }, 400);
                })
            }
            else{
                element.classList.add('card-active');
                element.addEventListener('mouseleave',()=>{
                    element.classList.add('leavin-mob');
                    
                    setTimeout(() => {                                         //  THESE DOESN'T
                        element.style.height = '38vh';
                        setTimeout(() => {
                        }, 400);
                    }, 400);
                })
            }

As one of the commenters noted, setTimeout is not a sleep kind of a method.正如一位评论者指出的那样, setTimeout不是一种sleep方法。

 setTimeout(() => {                                        
      element.style.height = '38vh';             
  }, 800);

Simply increase the timeout value if you need it later.如果以后需要,只需增加超时值。

To explain this further, a nested setTimeout is rare unless you are doing something in the second timeout, the code itself as you have written works fine but it has nothing to execute - it's also set to 400ms which is a super small time.为了进一步解释这一点,除非您在第二次超时中执行某些操作,否则嵌套setTimeout很少见,您编写的代码本身可以正常工作,但没有任何内容可以执行 - 它也设置为 400 毫秒,这是一个非常小的时间。 You can run the code below to see the second timeout works after 4 seconds.您可以运行下面的代码以查看 4 秒后的第二次超时工作。

setTimeout(() => {
  //  THESE DOESN'T
  console.log("This is 400ms!");
  //element.style.height = '38vh';
  setTimeout(() => {
    console.log(
      "This is 4 seconds but you usually would call something else here otherwise it has no effect or value"
    );
  }, 4000);
}, 400);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM