Search code examples
javascripthtmldhtmlx

Why doesn't setTimeout work as expected?


I am trying to move a <div id="box"> each time my mouse pointer hovers over it, but it appears to move only when I have the mouseover event on the div and not when my mouse hovers over it.

document.getElementsByTagName("body")[0].addEventListener("load",init());

function init(){
 console.log('in init');
 document.getElementById("box").addEventListener("mouseover",function(){
    var pixels=5;
    var perMs=40;
    var repeater=setTimeout(moveBox(pixels),perMs);

    document.getElementById("box").addEventListener("mouseout",function(){
        console.log('mouseOut');
        clearTimeout(repeater);
        });

    });

 }

 function moveBox(pixels){

    console.log('moveBox');
    var leftBox=document.getElementById("box").style.left;
    leftBox=parseInt(leftBox)+pixels;
    document.getElementById("box").style.left=leftBox;

  }

Solution

  • It appears as though you meant to use setInterval instead, to adjust the element on a repeated basis:

    var repeaterId = setInterval(moveBox, perMs, pixels);
    

    Read more about it here.