1

I have a pretty unique situation where I need a bunch of jQuery code to re-execute on a button click. The added complications are:

  • I can't allow the browser window to refresh
  • All the code is within a setTimeout() parameter - not sure if this really matters

I can't wrap the code inside a click event as it needs to run automatically on first opening or refresh of the page. To add a bit of context I've mocked up the following:

 setTimeout(function() {
     // all the scripts that need to run
 }, 2500);

 $('.btn').click(function() {
     // re-run the above code without refreshing window or browser
 });

Is there a way to re-run the code on a button click in this context?

Andyjm
  • 325
  • 3
  • 21
  • Possible duplicate of [How to write a reusable jquery click function?](http://stackoverflow.com/questions/22783420/how-to-write-a-reusable-jquery-click-function) – Bhojendra Rauniyar Oct 05 '16 at 11:47

4 Answers4

2

This is actually a fairly common issue.

Make a function that contains the code you need to run in both places, and call the function from the setTimeout and onclick handler:

function someCode () {
    // Your code here
} 

setTimeout (someCode, 2500);

$('.btn').click(someCode);

When in doubt, make a function.

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
2

put all your code that needs running in a function of its own and call the function in both places

function myFunc()
{
    // all the scripts that need to run
}

setTimeout(function() {
     myFunc();
 }, 2500);

 $('.btn').click(function() {
     myFunc();
 });
hairmot
  • 2,975
  • 1
  • 13
  • 26
  • You don't actually need to wrap `myFunc` in a function, you can simply pass in the function by reference to both the timeout and the click functions. – synthet1c Oct 05 '16 at 11:37
  • Had to choose the answer that came first but this is also a perfect solution so thanks! – Andyjm Oct 05 '16 at 11:51
1

What you can do is set the functions within a variable which can be called in both the setTimeout() and also on a click() event

var nameOfFunction = function() {
  console.log('Hello World!');
}
setTimeout(nameOfFunction, 2500);

 $('.btn').on('click', function(e) {
     e.preventDefault();
     nameOfFunction();
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="btn">Click Me</button>
Stewartside
  • 20,378
  • 12
  • 60
  • 81
1

Javascript objects are passed by reference so you can just reference the function by name in each of the callacks.

function myFunc(){
  // all the scripts that need to run
}

setTimeout(myFunc, 2500)

$('.btn').click(myFunc)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
synthet1c
  • 6,152
  • 2
  • 24
  • 39