Problems with setTimeout and addEventListener
hh
hh 2020-07-12 18:03:35
0
1
1205

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>

hh
hh

reply all(1)
Peter-Zhu

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template