Search code examples
javascripthtmlfunctionsleep

setTimeout function executing code without any delay . Javascript


Can anyone explain why this is happening. I have created a function in JS and trying to call it after 60 seconds using setTimeout function. But it runs right away after the page loads. Why is this happening and setTimeout is not delaying the function code? Below is the code.

<script>

function first()
{

document.getElementById('addProductText').style.color="#32A067";

}
setTimeout(first(),60000);

</script>

Solution

  • Use your call to the function without the brackets ():

    setTimeout(first, 6000);
    

    This way you are referencing to the function, and not calling it immediately.

    Working example:

    function first() {
      document.getElementById('addProductText').style.color = "#32A067";
    }
    setTimeout(first, 6000);
    <div id="addProductText">Hello World!</div>