📜  javascript setinterval - Javascript (1)

📅  最后修改于: 2023-12-03 15:16:06.870000             🧑  作者: Mango

JavaScript setInterval

In JavaScript, setInterval is a method used to repeatedly execute a function at specific time intervals.

Syntax
setInterval(function, delay, param1, param2, ...)
  • function: The function to be executed repeatedly.
  • delay: The time in milliseconds between each execution of the function.
  • param1, param2, ...: Optional parameters to be passed to the function.
Example
function sayHello(name) {
  console.log(`Hello ${name}`);
}

setInterval(sayHello, 1000, 'John');

In this example, the function sayHello is executed every 1000 milliseconds with the argument 'John'.

Return Value

setInterval returns an ID that can be used to stop the execution of the function using the clearInterval() method.

var intervalID = setInterval(sayHello, 1000, 'John');

// Stop execution after 5 seconds
setTimeout(function() { clearInterval(intervalID); }, 5000);

In this example, setInterval returns an ID that is stored in the intervalID variable. The clearInterval() method is used inside a setTimeout function to stop the execution after 5 seconds.

Conclusion

setInterval is a powerful method in JavaScript that allows developers to execute a function repeatedly at specific time intervals. By understanding its syntax and usage, you can create more dynamic and interactive web applications.