Reputation: 272
i am trying to do post AJAX request only once after color is set for more than 2 seconds.
[DEMO FIDDLE]
in the fiddle i want AJAX call to be fire only once after color is selected.
i don't want AJAX call to done on every click
how to do that?
Upvotes: 1
Views: 142
Reputation: 3665
You can simply add a flag to check if your code ran before.
var timeout;
var executed;
var arry = ['red', 'blue','orange', 'green'], i=0, len= arry.length;
$('#element').on('click',function(){
$(this).css('background',arry[i++]);
if(i===len){i=0;}
if(!executed){
clearTimeout(timeout);
timeout = setTimeout(function(){
alert("executed");
executed = 1;
}, 2000);
}
})
#element{
width:50px;
height:50px;
border:1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="element"></div>
Upvotes: 3
Reputation: 350
This can be done by just adding a condition in your click event as below
$(document).on("click", "#element", function () {
if ($('body').data("isServerHit") === undefined) {
$('body').data("isServerHit", true);
setTimeout(function () {
// Write the code for ajax call here
alert('server will hit now');
}, 2000);
}
});
For more details on $('body').data("isServerHit", true);
, visit save data (in jquery)
Hope this helps :)
Upvotes: 0
Reputation: 9380
As you want it to fire only once, bind .one()
instead of .on()
to the element. This will make the event execute only once.
And for delay, use setTimeout()
.
Upvotes: 4