Q8Y
Q8Y

Reputation: 4001

setinterval with click event is not working at all

I'm having a problem in letting 'setinterval' function to work in 'click' event. it doesn't work at all inside the click event, while if i put it out side the click event it works.. how can i get around this ??

I googled it for a solution, but it seems there is already an issue with it with the 'click' event.. & i hope you can help me guys with it..

thanks.

function myTimer() {
    alert("test");
};


$(document).ready(function() {  
    $('#testButton').click(function() {
        var myVar = setInterval(function() {
            myTimer();
        }, 1000);
    });
});

Sorry Guys... it seems that I was having an error on my side.. I put the input button to be runat server & this is was the problem... thank u guys for ur help.. and sorry for this problem ...

Upvotes: 0

Views: 2612

Answers (3)

Haroldo Gondim
Haroldo Gondim

Reputation: 154

Try:

var myTimer = function() {
    alert("test");
}

$(document).ready(function() {
    $('#testButton').click(function() {
        var reload = function() {
            setTimeout(function() {
                myTimer();
                reload();
            }, 1000);
        }
        reload();
    });
});

Upvotes: 0

jezzarax
jezzarax

Reputation: 413

Post your html code and check if jquery is included. You can also check if there're any errors in chrome console or firefox firebug. Your code works here if there's a button on a page

<button id="testButton">clickme</button>

Upvotes: 1

Tim Groeneveld
Tim Groeneveld

Reputation: 9019

Are you sure that you want to use setInterval? setInterval will run the same function all the time, until it is cleared.

Instead of defining a function inside the setInterval call, try just referencing myTimer, ie:

$('#testButton').click(function() {
    var myVar=setInterval(myTimer, 1000);
});

See 'setInterval' vs 'setTimeout'

Upvotes: 1

Related Questions