Chinovski
Chinovski

Reputation: 517

How to pause an event in Javascript?

I'm trying since yesterday with my js code but it still doesn't work. So I have a select list, when I change the selected option it calls an onchange event that calls a DWR function.

The problem is the DWR function takes a while and resets my select options (the first element selected instead of the one selected), I tried to set the previous value but it works only when I add a while loop.

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;

This is my code, it works but there is always an alert if I want to stop the script. Is there any way to replace this while instruction?

Upvotes: 1

Views: 1795

Answers (2)

Maxali
Maxali

Reputation: 1962

You can use setInterval which you can clear instead of while.

Your code can be like:

   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);

When you want to stop the event (interval) in this case, you set the stopCheking flag to true.

Upvotes: 2

Segimerus
Segimerus

Reputation: 516

You can "pause" functions with ES6 generators(yield keyword), but normally you should not need it in this case. Plain callback on the async call should do it.

Anyways here is the link for generators: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*

Upvotes: 0

Related Questions