如何在javascript中暂停一个事件?

时间:2016-11-17 10:09:36

标签: javascript jquery javascript-events

我从昨天开始尝试使用我的js代码,但它仍然无法正常工作。所以我有一个选择列表,当我更改所选选项时,它调用一个调用DWR函数的onchange事件。

问题是DWR函数需要一段时间并重置我的选择选项(选择的第一个元素而不是所选的一个),我试图设置前一个值但它只在我添加一个while循环时才有效。

var valeurTypeUo = document.getElementById('selectElement').value;
// DWR function called by this function
forme.getOptions(params);
// console.log(document.getElementById('typesUoChoix').value) is empty String
while (document.getElementById('typesUoChoix').value != valeurTypeUo)
    document.getElementById('typesUoChoix').value = valeurTypeUo;

这是我的代码,它可以工作,但如果我想停止脚本,总会有警报。有没有办法在指令时替换它。

提前谢谢。

2 个答案:

答案 0 :(得分:2)

您可以使用setInterval清除而不是while

您的代码可以是:

   var stopCheking = false;
   var checkingInterval; // interval holder

   var valeurTypeUo = document.getElementById('selectElement').value;

   // DWR function called by this function
   forme.getOptions(params);

   // console.log(document.getElementById('typesUoChoix').value) is empty String

   checkingInterval= setInterval( function() { 
     if( stopCheking ) clearInterval(checkingInterval);
   }, 2);

如果您想在此情况下停止活动(interval),请将stopCheking标记设为true

答案 1 :(得分:0)

您可以使用ES6生成器“暂停”函数(yield关键字),但通常在这种情况下您不需要它。异步调用上的普通回调应该这样做。

无论如何,这里是生成器的链接:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function *