Home >Web Front-end >JS Tutorial >Javascript timer - donghua-li's blog - CSDN blog

Javascript timer - donghua-li's blog - CSDN blog

一个新手
一个新手Original
2017-09-20 09:20:401424browse

By using JavaScript, we have the ability to execute code after a set interval, rather than immediately after the function is called. We call this a timing event. Provides two timer methods as follows:

  1. window.setInterval(); 这个方法就是在一个周期内反复执行一直到窗口关闭或者 clearInterval()
    window.setTimeout(); 延迟执行内容

How to use setInterval():

setInterval(code,millisec); 
code:可以是方法名,如果是方法不要加小括号。同时也可以是字符串用双引号将方法括起来。setInterval(“setCode()”,1000);或者setInterval(setCode,1000); 
millisec:是毫秒数,就是隔了多久执行

The code is as follows:

 var p1 = document.getElementById("p");    
 var n = 0;    
 var data = ["4234","343440"];    
 var rows = 0;    
 var cols = 0;    
 function setCode(){
        if(cols < data[rows].length){
            p1.innerHTML += data[rows][cols];
            cols++;
        }else if(rows < data.length){
            p1.innerHTML += "</br>";
            rows++;
            cols = 0;
        }else {
            clearInterval(timer);
        }
    }    var timer = setInterval(setCode,500);

The usage of setTimeout and setInterval is the same.


So can parameters be passed in the timer? The answer is no, so what should we do? It is recommended to use anonymous functions.

The code is as follows:

   var person = {name: "peng", age: 23};    
   function getPerson(person){
        alert(person.name);
    }    var timer = setInterval(function(){
        getPerson(person);
    },1000);

It is defining the timer and rewriting a function to call the method in the function.
Of course, you can also directly enclose the function and parameters with "", but this will not allow you to change the parameter values ​​periodically.

The above is the detailed content of Javascript timer - donghua-li's blog - CSDN blog. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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