1

I have next code structure:

global.js and *.js for each page. Lets take for example global.js and main_menu.js.

I have some elements, that have class ripple_effect, when elements with this class get clicked, the animation begins that runs 650ms, so in order to let users see the animation i try to make a small delay in code ( i know this is not good, but still ).

in global.js i have next code:

var delayForRipple = 300;

function Execute(func) {
    setTimeout(func(), delayForRipple);
}

in main_menu.js i have next code:

$(this).on('click', ".menu_button", function (e) {
        href = $(this).attr('id');
        Execute(function () {
            window.location.href = href;
        });
    });

But this code executes immediately. How can i fix it?

Here is a fiddle for fast reproduction:

var delayForRipple = 300;

$(".wrapper").on('click', "#clickMe", function (e) {
    Execute(function () {
        alert("TEST");
    });
});

function Execute(func) {
    setTimeout(func(), delayForRipple);
}
.test_element {
    height:100px;
    width:100px;
    background-color:red;
}
<div class="wrapper">
    <div id="clickMe" class="test_element"></div>
</div>

3
  • 1
    setTimeout expects a function reference (or a string), but you're calling func(), which doesn't return a reference, it just redirects ... Commented Nov 27, 2015 at 19:27
  • actually 300 ms is very short, you can't hardly see the delay. maybe you try with a higher number of ms Commented Nov 27, 2015 at 19:27
  • @mapodev tried more, set it to 10000 - still the same Commented Nov 27, 2015 at 19:28

3 Answers 3

2

You are doing wrong ... you have to pass callback to setTimeout to be executed and not execute it yourselt there

Do something like

function Execute(func) {
   setTimeout(func, delayForRipple);
}

Or even remove the redundant Execute function

$(".wrapper").on('click', "#clickMe", function (e) {
   setTimeout(function () {
      alert("TEST");
   }, 650);
});
Sign up to request clarification or add additional context in comments.

2 Comments

this is not redundant, i will use this functions on many other pages - that is why i dont want to duplicate the setTimeout
thanks, now i understood how this works. this will help me further. your answer is correct
2

This works.

function Execute(func) {
    setTimeout(func, 2000);   
}

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

1 Comment

yes, thanks, Zohaib Ijaz was faster so i'm marking his answer as correct one, but will give you an upvote.
1

Change func() to func in setTimeout

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.