user3320550
user3320550

Reputation: 123

Javascript run function on setInterval and click

Currently, I am running a function every five seconds.

setInterval(function(){loadLog()},5000);

However, how can I also run the function on demand (on the click of a button) without having to wait for the intervals?

I think that I MAY need to use something like clearInterval, but I'm not sure.

Upvotes: 0

Views: 690

Answers (2)

Tony Scapardine
Tony Scapardine

Reputation: 1

Rather than putting your function within the setInterval why don't you just write your function:

function loadLog() {
    //do something
};

and then call the function within the setInterval and also on the click event of your button:

setInterval(loadLog, 5000);
$('#button').click(loadLog);

at least this worked for me

Upvotes: 0

jfriend00
jfriend00

Reputation: 707238

You can just use a click event handler:

 <button id="runLog">Run Now</button>

Javascript:

 document.getElementById("runLog").addEventListener("click", loadLog);

Upvotes: 1

Related Questions