Home  >  Q&A  >  body text

Problems with setTimeout and addEventListener

This is code written on a rookie;

setTimeout no matter how long it is set, the final result will appear directly in innerHtml;

Why is this

##<!DOCTYPE html>

<html>

<head>

<meta charset= "utf-8">

<title>Rookie Tutorial (runoob.com)</title>

</head>

<body>

The document adds an onmousemove event handler, which will display random numbers when the mouse is moved in the document.

Click the button to remove the event handler.

<button id='demo1'>Click me</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 days ago1155

reply all(1)I'll reply

  • 天蓬老师

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

    The callback function of setTime() is executed asynchronously. Only when the main call stack is cleared will it enter the call stack from the task queue, so the situation you mentioned will occur

    reply
    0
  • Cancelreply