导航
×
   ❮   
HTML CSS JavaScript PHP Go Sass W3C Colors ECMS

JS 教程

JS 简介 JS 如何使用 JS 输出 JS 语法 JS 语句 JS 注释 JS 变量 JS 运算符 JS 条件语句 JS 循环 JS 字符串 JS 数字 JS 函数 JS 对象 JS 日期 JS 数组 JS 类型化数组 JS 集合 JS Map 映射 JS Math JS 正则表达式 JS 数据类型 JS 错误 JS 事件 JS 编程 JS 关键字参考 JS 保留关键字参考 JS 运算符参考 JS 运算符优先级 JS UTF-8 字符 JS UTF-8 符号 JS UTF-8 表情符号 JS 版本

JS 高级教程

JS 对象 JS 函数 JS 类 JS 迭代 JS Promises JS 模块

JavaScript 异步编程


等待超时

在使用 JavaScript 函数 setTimeout() 时,可以指定超时时执行的回调函数:

实例

setTimeout(myFunction, 4000);

function myFunction() {
  document.getElementById("demo").innerHTML = "I love You !!";
}

亲自试一试 »

若不将函数的名称作为参数传递给另一个函数,您始终可以传递整个函数:

在上面的示例中,myFunction 被用作回调。

函数(函数名)作为参数传递给 setTimeout()

3000 是超时前的毫秒数,所以 3 秒后会调用 myFunction()

当您将函数作为参数传递时,请记住不要使用括号。

正确:setTimeout(myFunction, 3000);

错误: setTimeout(myFunction(), 4000);


等待间隔:

在使用 JavaScript 函数 setInterval() 时,可以指定每个间隔执行的回调函数:

实例

setInterval(myFunction, 1000);

function myFunction() {
  let d = new Date();
  document.getElementById("demo").innerHTML=
  d.getHours() + ":" +
  d.getMinutes() + ":" +
  d.getSeconds();
}

亲自试一试 »

在上面的例子中,myFunction 用作回调。

函数(函数名)作为参数传递给 setInterval()

1000 是间隔之间的毫秒数,因此 myFunction() 将每秒调用一次。


等待文件

如果您创建函数来加载外部资源(如脚本或文件),则在内容完全加载之前无法使用这些内容。

这是使用回调的最佳时机。

此例加载一个 HTML 文件 (mycar/),并在文件完全加载后在网页中显示该 HTML 文件:

等待文件:

function myDisplayer(id, some) {
  document.getElementById(id).innerHTML = some;
}

function getFile(file, callback, id) {
  xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
     callback(id, this.responseText);
    }
  }
  xhttp.open("GET", file, true);
  xhttp.send();
}

getFile("mycar/", myDisplayer, "demo");

亲自试一试 »

在上面的示例中,myDisplayer 用作回调。

函数(函数名)作为参数传递给 getFile()

以下是 mycar/ 的副本:

mycar/


<img src="img_car.jpg" alt="Nice car" style="width:100%">

<p>A car is a wheeled, self-powered motor vehicle used for transportation.
Most definitions of the term specify that cars are designed to run primarily on roads,to have seating for one to eight people, to typically have four wheels.</p>

<p>(Wikipedia)</p>
 

Copyright ©2020-2026 freew3c.com All Rights Reserved 提供的内容仅用于学习和测试,不保证内容的正确性。