0

I have a timer which triggers a function each 3 seconds using setTimeout or setInterval. The point is that I need to execute the countdown before the function instead of execute the function first and then the timer.

This is the code:

var timer;

document.getElementById('myBtn').addEventListener('mousedown', function (){
    timer = setInterval(alert("Ey, release the button!"), 3000);
});

And this should be the order of actions:

  1. Click and hold the button.
  2. Start the countdown ...3, 2, 1...
  3. Trigger the function.

2 Answers 2

2

You could trigger another function at the end of the timer. Since you only need to call it once.. You could just use setTimeout

document.getElementById('myBtn').addEventListener('mousedown', function (){
    alert("Ey, release the button!")
    setTimeout(fireMe, 3000);
});

function fireMe() {
    // Boom
}

You might also want to add clearTimeout on mouseup event.

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

Comments

1

Do something like

var timer;

   document.getElementById('myBtn').addEventListener('mousedown', function (){
     timer = setTimeout(function(){
       alert("Ey, release the button!");
     }, 3000);
});

5 Comments

Errm.. what's the difference?
The difference is that the alert-call is wrapped in a function in this code so it will be passed as a callback. In the OPs code it's not so it will be evaluated and then the result from alert will be passed on to setInterval which would be useless.
You have to pass a callback inside setInterval function as first argument which is then called after 3000 milliseconds but you executed the statement there.
This will alerts every 3 seconds not once.
@mortezaT The whole idea was to tell how to call the alert. However I modified my answer

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.