Reputation: 22490
I have one simple print function using setInterval
. When clicking the first p
it displays the "first" value correctly but clicking the second value was blinking. The first and second values were continuously printing with blinking. It's my problem. Please help me stop the blinking and correctly print the second value.
$(document).on('click', 'p', function() {
var key = $(this).html();
setInterval(function() {
$('#demo').load('e1.php?hash=' + key);
}, 200);
//e1.php(<?php echo $_REQUEST['hash'];?>)
});
<p>first!</p>
<p>second!</p><br><br><br><br>
<div id="demo"></div>
Upvotes: 2
Views: 1286
Reputation: 1074028
You're creating a new recurring callback on each click. So after one click, you have a recurring load of that key
; after a second click, you have a recurring load of that key
as well, and the two intermix chaotically. A third click adds a third recurring callback into the mix.
If you just want something to happen once after a brief delay, use setTimeout
, not setInterval
:
$(document).on('click', 'p', function(){
var key = $(this).html();
setTimeout(function() { // Just do it *once*
$('#demo').load('e1.php?hash='+key);
}, 200);
});
If you want it to recur, but only with the new key
, then you need to store the handle of the previous timer and cancel it before starting the new recurring timer:
var loadHandle = 0; // 0 is an invalid handle we can clear safely
$(document).on('click', 'p', function(){
clearTimeout(loadHandle);
var key = $(this).html();
loadHandle = setInterval(function() {
$('#demo').load('e1.php?hash='+key);
}, 200);
});
Alternately, just store the most recent key outside the closure so that the interval picks it up:
var key = null;
$(document).on('click', 'p', function(){
if (key === null) {
// First click, start the recurring callback
setInterval(function() {
$('#demo').load('e1.php?hash='+key);
}, 200);
}
// Remember the (new) key that callback should use
key = $(this).html();
});
Upvotes: 3