GhostKU
GhostKU

Reputation: 2108

How to `wait` in JavaScript

I have a small Chrome Extension written in javascript with jQuery that should grab some data from a web page. Target HTML looks like:

<div id="options">
  <div class="option"><div class="checkbox">1</div></div>
  <div class="option"><div class="checkbox">3</div></div>
  <div class="option"><div class="checkbox">5</div></div>
  <div class="option"><div class="checkbox">Other value</div></div>
  ...
</div>
<div id="result">0</div>

When any of .checkbox is checked #result will change. My task is to check .checkbox one by one and get #result for each.

var result = {};
// for each checkbox
$('#options .option').each(function(){
  // check it
  this.click()
  // wait a bit. Of course ideally if we can wait while #result is not changed but in practice sometimes checkbox doesn't change the result. So it will be enough to wait a few seconds
  // store data
  result[this.text()] = $('#result').text();
  // uncheck the checkbox
  this.click()
  // wait
});
console.log(result);

Any ideas how to wait correctly? Thanks

UPD: A little example that show my problem https://codepen.io/mihajlo-osadchij/pen/MNyazz

Upvotes: 0

Views: 139

Answers (2)

mwilson
mwilson

Reputation: 12970

As others are saying, you should use event handlers instead of doing a manual wait. Here is a basic example of how to bind a change event to get the value of the checkbox that has changed.

If you did use something like setTimeout, you would quite literally be purposefully slowing down your application due to bad design.

$('.checkbox').on('change', (evt) => {
	console.log(evt.target.value);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="checkbox" value="1" />
<input type="checkbox" class="checkbox" value="2"  />
<input type="checkbox" class="checkbox" value="3"  />
<input type="checkbox" class="checkbox" value="4"  />

Upvotes: 1

blurfus
blurfus

Reputation: 14041

I believe you want to use an event handler instead of waiting for a bit to see if the checkbox was clicked on.

Since you are already using jQuery, it could be as simple like the demo below:

$(function(){
  $(".checkbox").on('click', function(){
     $("#result").text( $(this).text());
  });
});
.option{  
   width: 100px;
   height: 15px;
   border: 1px solid gray;
   padding: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="options">
  <div class="option"><div class="checkbox">1</div></div>
  <div class="option"><div class="checkbox">3</div></div>
  <div class="option"><div class="checkbox">5</div></div>
  <div class="option"><div class="checkbox">Other value</div></div>  
</div>
Results: <span id="result">0</span>

Upvotes: 0

Related Questions