2

I have unknown problem with my small function "tap and hold". Could anyone tell me what is wrong? Thanks for help.

<!DOCTYPE html>
<html>
<body>
<button id="seconds">30</button>

<script type="text/javascript">


var timeoutId = 0;

$('#seconds').on('mousedown', function() {
timeoutId = setTimeout(alert("something"), 1000);
}).on('mouseup mouseleave', function() {
clearTimeout(timeoutId);
});

</script>
</body>
</html>
I_love_pugs
  • 103
  • 6

1 Answers1

4

The problem is that your alert is being invoked immediately. You need to pass a function to setTimeout, not call a function. I've refactored your code to make it a function and now the alert will show after 1 second if you don't move your mouse.

var timeoutId = 0;

$('#seconds').on('mousedown', function() {
  timeoutId = setTimeout(function(){alert("something")}, 1000);
}).on('mouseup mouseleave', function() {
  clearTimeout(timeoutId);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="seconds">30</button>
Jordan Soltman
  • 3,795
  • 17
  • 31
  • Hi @Jordan, what is the difference by a call function and a function ? Could you explain how the example works? – user305883 Aug 17 '17 at 14:00
  • 1
    setTimeout is expecting a function that it can call after 30 seconds as the first argument. The user originally passed alert() which is a call to a function. alert is the function. So by wrapping the alert in a lambda or anonymous function, we are giving setTimeout a function it can call when it needs to. – Jordan Soltman Aug 17 '17 at 14:22