简体   繁体   English

我想在 10 秒后停止运行

[英]I want to stop this running after 10 seconds

  • I tried using setTimeout(clearInterval(MY_INT, 10000) in the function olo() but it ran only once and stopped:/ Where could I put it or should I use for()?我尝试在 function olo() 中使用 setTimeout(clearInterval(MY_INT, 10000),但它只运行了一次就停止了:/ 我可以把它放在哪里,还是应该使用 for()?

There is no <script src></script> tag because I am using online editor.没有<script src></script>标签,因为我使用的是在线编辑器。 If you guys know how to make VScode like an online editor please suggest.如果你们知道如何使 VScode 像在线编辑器一样,请提出建议。 * *

const btn = document.getElementById('Button');
const target = document.getElementById('here');

btn.addEventListener('click', ()=>{
  
  
  function olo(){
  let loadingImage = document.createTextNode('**');
  target.appendChild(loadingImage);
    
  
  }

  const MY_INT = setInterval(olo ,1000)
})
<!DOCTYPE html>
<html>
<head>
  
  <title>Loading...</title>
</head>
<body>
  <div>
   
    <button id='Button'>load</button>
    <h1 id='here'></h1>
  </div>
</body>
</html>
  1. The 10000 argument should be in setTimeout s parameters, but you have it in clearInterval . 10000参数应该在setTimeout的参数中,但你有它在clearInterval中。

  2. You should not place it in the olo function, it should be right after you set the interval.您不应该将它放在olo function 中,它应该在您设置间隔之后。

  3. setTimout expects a callback, you have provided it a function call, change clearInterval(MY_INT) to an anonymous function (or any function, but NOT a function call). setTimout expects a callback, you have provided it a function call, change clearInterval(MY_INT) to an anonymous function (or any function, but NOT a function call). eg () => clearInterval(MY_INT)例如() => clearInterval(MY_INT)

Full cleanup of your code with the fixes above (i tweaked the timings slightly to make it easier to play with):使用上面的修复程序完全清理您的代码(我稍微调整了时间以使其更易于使用):

btn.addEventListener("click", () => {
  function olo() {
    let loadingImage = document.createTextNode("*");
    target.appendChild(loadingImage);
  }

  const MY_INT = setInterval(olo, 500);
  setTimeout(() => clearInterval(MY_INT), 3000);
});

Sandbox with fix 带修复的沙箱

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

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