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?

1

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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();
 });

2 Comments

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.
Had to choose the answer that came first but this is also a perfect solution so thanks!
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>

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.