首页  >  问答  >  正文

setTimeout 跟addEventListener问题

这是放在菜鸟上写的代码  ;

setTimeout 无论设置多长时间 ,innerHtml都是直接出现最终结果;

这是为啥呢

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<title>菜鸟教程(runoob.com)</title>

</head>

<body>

文档添加 onmousemove 事件句柄,当在文档中移动鼠标时会显示随机数。

点击按钮移除事件句柄。

<button id='demo1'>点我</button>

<p id="demo">

<script>

document.getElementById("demo1").addEventListener("click", myFunction);

var time = 5;

function myFunction() {

    document.getElementById("demo").innerHTML = time;

removeHandler(time);

}

function removeHandler(i) {

i--;

document.getElementById("demo").innerHTML = i;

setTimeout(removeHandler(i),1000);

}

</script>

</body>

</html>

hhhh1560 天前1154

全部回复(1)我来回复

  • 天蓬老师

    天蓬老师2020-07-17 19:57:46

    setTime()的回调函数是异步执行,只有主调用栈清空才会从任务队列进入调用栈,所以就会出现你说的这种情况

    回复
    0
  • 取消回复