To stop a running function in JavaScript by clicking a button, you can use the clearInterval() method.

First, you need to declare a variable to store the interval ID returned by the setInterval() method when you start the function.

Then, you can create a button with an onclick event handler that calls the clearInterval() method and passes the interval ID variable as an argument.

Here's an example:

// Declare a variable to store the interval ID
let intervalId;

// Function to run
function myFunction() {
  // Code goes here
}

// Start the function and store the interval ID
intervalId = setInterval(myFunction, 1000);

// Button to stop the function
const stopButton = document.querySelector('#stop-button');
stopButton.onclick = function() {
  clearInterval(intervalId);
}

In this example, the setInterval() method starts the myFunction() function and runs it every 1000 milliseconds (1 second). The clearInterval() method is called when the user clicks the button with the ID "stop-button". This stops the function from running.

how to stop a ruuning function in js by clicking button

原文地址: https://www.cveoy.top/t/topic/bcQN 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录