栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在JavaScript循环中添加延迟?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在JavaScript循环中添加延迟?

setTimeout()
函数是非阻塞的,将立即返回。因此,您的循环将非常快速地迭代,并且将快速连续地发起3秒超时触发。这就是为什么您的第一个警报会在3秒钟后弹出,而其余所有警报都将连续不断地出现。

您可能要改用以下方式:

var i = 1;          //  set your counter to 1function myLoop () {//  create a loop function   setTimeout(function () {    //  call a 3s setTimeout when the loop is called      alert('hello');          //  your pre here      i++;          //  increment the counter      if (i < 10) { //  if the counter < 10, call the loop function         myLoop();  //  ..  again which will trigger another       }  //  ..  setTimeout()   }, 3000)}myLoop();//  start the loop

您也可以通过使用自调用函数将迭代次数作为参数来修饰它:

(function myLoop (i) {  setTimeout(function () {         alert('hello');          //  your pre hereif (--i) myLoop(i);      //  decrement i and call myLoop again if i > 0   }, 3000)})(10);  //  pass the number of iterations as an argument


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/398717.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号