Home > Web Front-end > JS Tutorial > body text

Usage of setInterval in javascript_javascript skills

WBOY
Release: 2016-05-16 15:49:46
Original
1535 people have browsed it

The setInterval function in JavaScript is mainly a function that calls the operation method at a certain time interval when creating animation or other interval rendering (operation) effects.

The main expression formats of setInterval are:

setInterval(fnname,time,par1,par2,.........parn);

setInterval(obj,fnname,time,par1,par2,...parn);

The first is the most common expression syntax, where the fnname parameter can be a reference to an anonymous function or a function name, time is the set time interval for calling faname, in milliseconds, and the default value is 10 milliseconds. par1......parn is an optional parameter and is the parameter passed to the faname method.

The second is to use the syntax of object methods. The faname parameter is the method of the obj object. The other parameters are the same as the first syntax.

The following uses examples to explain:

//普通语法的第一种写法

setInterval(function(){
    alert("我是setInterval方法打印结果");
  },3000) //每隔3秒打印一次

//普通语法的第二种写法

function alert1(){
    alert("我是setInterval方法打印结果")
  }
function alert2(str){
    alert(str);
  }
  setInterval(alert1,3000);
  setInterval("alert1()",3000);
  setInterval(alert2,3000,"我是setInterval方法打印结果");
  setInterval("alert1()",3000,"我是setInterval方法打印结果");

//对象方法写法

obj = new Object();//创建一个新的对象

obj.alert1 = function(){
    alert("我是setInterval方法打印结果");
  }

obj.alert2 = function(str){
    alert(str);
  }

setInterval(obj,alert1,3000);
setInterval(obj,alert2,3000,"我是setInterval方法打印结果");

Copy after login

setInterval is generally used in conjunction with clearInterval. The function of clearInterval is to clear the call to the setInterval method. The parameter of clearInterval is the return value of setInterval.

var timer = setInterval(obj,alert1,3000);

clearInterval(timer);
Copy after login

The above is the entire content of this article, I hope you all like it.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!