2016-12-24 75 views
-2

我有两个功能,x()和'Y(),点击其按钮,buttonXbuttonY他们两个调用,并呼吁暂停实际行动停止两个功能有超时。我想达到什么:启动和使用两个按钮

  1. buttonX被点击,功能y()不执行任何更长的时间,并且功能x()被称为 - 有超时;
  2. 按钮Y被点击时,功能x()不再执行,并且函数y()被调用 - 带有超时;

该怎么办?

HTML

<button onclick = "x()">button1</button> 
<button onclick = "y()">button2</button> 

JS

function x(){ 
    // dosomething; 
    // stop execution of y() 
    setTimeout(x,2000); 
} 
        } 
function y(){ 
    // dosomeother thing; 
    // stop execution of x() 
    setTimeout(y,2000); 
} 
+3

请添加代码,你必须在这里看看,太:MCVE] –

+0

尝试设置变量'timeoutX = setTimeout的()',那么你可以通过调用取消' clearTimeout(timeoutX)'。对于timeoutY可以做同样的事情。 –

回答

1

我会通过调节接近它的一些布尔值,即:

HTML

超时内两个动作
<button id="firstFunction">Run first function</button> 
<button id="secondFunction">Run second function</button> 

JS

var callFirstFunction = true; 
var callSecondFunction = true; 

document.getElementById("firstFunction").addEventListener("click", function(e){ 
    callFirstFunction = true; 
    callSecondFunction = false; 
    setTimeout(function(){ 
    if(callFirstFunction) { 
     //your first function action 
    } 
    }, 10000); 
} 

document.getElementById("secondFunction").addEventListener("click", function(e){ 
    callSecondFunction = true; 
    callFirstFunction = false; 
    setTimeout(function(){ 
    if(callSecondFunction) { 
     //your second function action 
    } 
    }, 10000); 
} 
0

这里是你使用clearTimeout功能是怎么做的。它比在回调函数中使用if语句更简洁一些,因为回调函数被完全取消。

var timeoutOne; 
 
var timeoutTwo; 
 

 
function x(){ 
 
    clearTimeout(timeoutTwo); 
 
    timeoutOne = setTimeout(function(){ 
 
    alert("Button One Pressed");   
 
    }, 1000); 
 
} 
 

 
function y(){ 
 
    clearTimeout(timeoutOne); 
 
    timeoutTwo = setTimeout(function(){ 
 
    alert("Button Two Pressed");   
 
    }, 1000); 
 
}
<button onClick="x()">Button One</button> 
 
<button onClick="y()">Button Two</button>