1

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>
Faisal Shani
  • 698
  • 1
  • 13
  • 37

2 Answers2

1

You should only pass the name of the function without calling it:

function first(){
     console.log("Hello")
}
setTimeout(first, 60000);
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
  • You actually don't have to give the name of a function, you have another alternative that could also provide a function operating multiple instructions before calling the target function. See https://repl.it/repls/BelovedShallowBusinesssoftware/ – Amin NAIRI Apr 09 '20 at 20:26
  • What is important to do in order to prevent premature calls is that you give the reference of a function, whether it is the target function or an anonymous one. – Amin NAIRI Apr 09 '20 at 20:28
1

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>
Tamas Szoke
  • 5,426
  • 4
  • 24
  • 39