2013-10-06 29 views
0

我想禁用我的下拉列表,而我的颜色(间隔)正在发射。在我的情况下,我会在5秒后手动设置截断值。我所经历的是,当我将重新激活器放在我的大小写区块中时,它不会等待setTimeout。或者两个电话都在同一时间触发,所以在setTimeout正在触发时(又等待那五秒钟),下一个电话(再激活器)也会触发?函数立即执行,而不是等待setTimeout

另一个问题 - 以及我希望在我的颜色正在启动时停用下拉菜单的原因 - 我注意到,在颜色正在触发时,如果我再次单击下拉菜单,则-aka将再次打电话给它,第二次调用将导致颜色无休止地触发(假设以某种方式创建了无限循环)。思考为什么?

function timeToHexColor(){ 
    var time = new Date(); 
    var timestamp = time.toString("hh:mm:ss"); 
    document.getElementById("board").innerHTML += 
           "#" + timestamp.split(":").join("") + "<br/>"; 
} 

function Colors(interval) { 
    this.interval = interval; 
    switch (this.interval) { 
     case 'second': 
      document.getElementById('options').disabled = true; 
      x = setInterval(timeToHexColor,1000); 
      setTimeout(stopColors, 5000); 
      //Placing the re-activtor here executes instantly not after the setTimeout. 
      //document.getElementById('options').disabled = false; 
      break; 
     case 'minute': 
      x = setInterval(timeToHexColor,60000); 
      setTimeout(stopColors, 5000); 
      document.getElementById('options').disabled = true; 
      break;  
     case 'hour': 
      x = setInterval(timeToHexColor,60000*60); 
      setTimeout(stopColors, 5000); 
      document.getElementById('options').disabled = true; 
      break; 
     case 'day': 
      x = setInterval(timeToHexColor,60000*1440); 
      setTimeout(stopColors, 5000); 
      document.getElementById('options').disabled = true; 
      break; 
     default: 
    } 
} 

function stopColors() { 
    clearInterval(x); 
    //Placing the re-activator here instead works they way I intended, 
    //after the repeat cycle is finished. 
    document.getElementById('options').disabled = false; 

} 
$("#options").prop('selectedIndex',-1); 
$("#options").change(function() { 
    Colors('second'); 
}); 
+0

您需要在stopColors函数中启用“选项”。否则这是不可能的 – Tuxes3

+2

'javascript'和'multithreading'标签在一个问题中,你没有看到每一天:D – skmasq

回答

1

我想你期待setTimeout暂停执行代码。这不是setTimeout。它会将您传递给它的函数安排在稍后执行并立即返回。

如果你想构建你的代码,这样再活化位于switch语句附近,而不是stopColors可以使用匿名函数:

document.getElementById('options').disabled = true; 
x = setInterval(timeToHexColor,1000); 
setTimeout(function(){ 
    stopColors(); 
    document.getElementById('options').disabled = false; 
}, 5000); 

你会发现,这是完全一样把活化器内stopColors,但现在它不在stopColors中硬编码(可能使该函数更可重用?)。所以它基本上是一个您希望获得激活码的风格问题。 setTimeout背后的机制仍然工作相同。

请注意JavaScript是单线程的。这就是为什么像setTimeoutXMLHTTPrequest这样的函数按照他们的方式工作 - 继续执行javascript直到脚本结束,然后在稍后浏览器执行给定函数。如果您尝试暂停执行,则浏览器将不会获得处理时间来执行绘制到屏幕或接受用户点击或下载ajax响应等操作。

+0

感谢slebetman笔记,可能是一个非常疯狂的想法,但我的印象是'调度“本身就是sitTimeout函数的执行,因此调度本身就是一个过程。 – brooklynsweb