user1019042
user1019042

Reputation: 2218

jquery how to stop settimeout from looping

I want after my page loads to do a trigger click once and only once. many posts swear that settimeout only fires once, but in my case it is infinite! here is one of my many trials.

$( document ).ready(function() {
    setTimeout(function() {
        $("#btn1").trigger('click');
    },1000);
});

I have tried moving that into a function outside the document.ready and then add cleartimeout, but then it stops from firing at all:

$( document ).ready(function() {
    test();
});
function test() {
    var t = setTimeout(function() {
        $("#btn1").first().trigger('click');
    },1000);
    clearTimeout(t);
}

What am I doing wrong!?

Upvotes: 0

Views: 769

Answers (2)

suneetha
suneetha

Reputation: 827

use clearTimeout() inside the setTimeout().It clears the timeout after triggering the click

$(document).ready(function() {
 test();
});
function test() {
  var t = setTimeout(function() {
  $("#btn1").trigger('click');
  clearTimeout(t);
 }, 1000);
}
$("#btn1").on('click',function(){
 console.log("Clicked");
});

Fiddle: http://jsfiddle.net/6G4pR/

Upvotes: 1

mcn
mcn

Reputation: 721

use e.stopPropagation(), this might be because of event bubbling.

HTML

<button id="btn1">my button</button>

JS

$( document ).ready(function() {
    setTimeout(function() {
        $("#btn1").trigger('click');
    },1000);

  $("#btn1").click(function(e){
    console.log('clicked');
    e.stopPropagation();
    console.log(e);
  })
});

CODE

Upvotes: 0

Related Questions