How to stop setInterval execution in JavaScript?
Hello everyone! I'm a beginner in JavaScript and ran into a problem. I have a function that updates data on the page every 5 seconds. I use setInterval for this:\n\n```javascript\nfunction updateData() {\n console.log('Data updated');\n}\n\nsetInterval(updateData, 5000);\n```\n\nEverything works fine, but now I need to stop this interval when the user clicks the "Stop" button. I tried writing this:\n\n```javascript\nlet interval = setInterval(updateData, 5000);\n\nfunction stopInterval() {\n clearInterval(interval);\n}\n```\n\nBut for some reason the interval doesn't stop. Maybe I'm saving the interval ID incorrectly? Or does clearInterval not work the way I think? Please tell me how to properly stop setInterval. I would be grateful.
No answers yet.
Log in to leave an answer
Blogs