2017-11-03 66 views
0

当我在javascript中循环访问数组时,我在每个项目后暂停3秒。它成功地完成了这项工作,但它冻结了网页,直到数组完成。页面在循环中停留3秒时冻结

function launchTutorial() { 
     HideFloatingMenu(); //freezes on page and it doesn't when i comment out the subsequent array loop 
    //highlightElement("diLeftColumn"); 

//the classes of each element to highlight in the tutorial 

    var tutorialClasses = [ 
     "diLeftColumn", 
     "diMiddleColumn", 
     "diRightColumn" 
    ]; 

    var threeSec = new Date().getTime() + 3000; 
    for (var i = 0; i < tutorialClasses.length; i++) { 
     //$.each(tutorialClasses, function (key, value) { 

     if (i != 0) { 
      var now = new Date().getTime(); 
      if (now >= threeSec) { 
       highlightElement(tutorialClasses[i]); 
       threeSec = new Date().getTime() + 3000; 
      } 
      else { 
       i = i - 1; //go back to this item if it hasn't been 3 seconds 
      } 
     } 
     else { 
      highlightElement(tutorialClasses[i]); 
      threeSec = new Date().getTime() + 3000; 
     } 
    } 
} 

我已经试过的setTimeout(),setInterval的(0,延迟(),2个不同的自定义睡眠功能,并且while循环,没有一次成功。

+1

什么东西'事件loop'什么东西,好吗所以现在有,因为你做的一切是同步的,你挡住你的执行已经结束了,我想看看你的setTimeout ()实现,因为这将是正确的方式去做这个“延迟”(虽然它不会是完美的,JSYK,但可能够好!) –

+0

它只是返回“functionGenerator = undefined”当我通过它。 – Rainhider

回答

0

使用此。在JavaScript中,当你做一个需要时间x的while循环,整个页面冻结了那个时间x,所以使用while循环是没有选择的,但是你可以像这样使用setTimeout函数,这将每10秒运行一次printNextElement函数(在我的例子中)。

在console.log处,做你的逻辑,把你的时间改为10000.

const ar = ['Hello', 'World']; 
 
let index = 0; 
 

 
const printNextElement =() => { 
 
    console.log(ar[index]); 
 
    index += 1; 
 
    
 
    if(ar.length === index) { 
 
    return; 
 
    } 
 
    
 
    window.setTimeout(printNextElement, 10000); 
 
}; 
 
    
 
printNextElement();

+0

非常感谢你!像梦一样运行,不会冻结页面! – Rainhider