0

i have this simple page:

 <!DOCTYPE html> <html> <body> <p>Click the second button to skip the timeout!</p> <button onclick="myStopFunction()">Stop the alert</button> <script> var myVar; spamHi(); function spamHi() { console.log("Hi!"); setTimeout(spamHi,3000); } function myStopFunction() { clearTimeout(spamHi); } </script> </body> </html> 

The function spamHi() prints "Hi!" in the console every 3 seconds. What the function myStopFunction() is supposed to do is to clear the delay to enable the console to print "Hi!" immediately without waiting the 3 seconds.

How can i fix this?

1
  • You might want to look into setInterval instead of constantly resetting your timeout. The provided answer is correct through in either case, you need to store the ID of the timeout or interval and clearTimeout or clearInterval to stop it. Commented Sep 24, 2019 at 18:58

1 Answer 1

2

You need to get the return of the setTimeout call and then pass it to the clearTimeout function:

var timeout = setTimeout(spamHi, 3000); clearTimeout(timeout); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.