-2

I'm trying to use setTimeout to perform document.write after a certain delay after a form is submitted. For now, the delay is a static 3000ms. However, when I try to implement it, document.write happens instantly. How can I implement setTimeout correctly?

This is for a website. Form submission happens before this block of code runs, and variables are passed from what is submitted.


function findInterval(){
var delay = document.forms["options"]["delay"].value;
min = Math.ceil(min);
max = Math.ceil(max);
var result = Math.floor(Math.random() * (max - min + 1)) + min;
var total = parseInt(delay) + parseInt(result);
setTimeout(document.write(total), 3000);
}

My understanding is that my code should wait 3 seconds, then do document.write(total) but that's not the case. What am I doing wrong?

Yasir C
  • 83
  • 1
  • 13

1 Answers1

2

The first paramter of setTimeout is a callback function.

setTimeout(function(){document.write(total)}, 3000);
Khalid Ali
  • 1,224
  • 1
  • 8
  • 12
  • There is a related answer here: https://stackoverflow.com/questions/9184702/settimeout-not-delaying-a-function-call. – Danny Fardy Jhonston Bermúdez Apr 19 '19 at 00:38
  • Thank you for the answer, I appreciate it. Looking at the duplicate question helped too. However, my new line of code is: `setTimeout(function(){document.write(total);}, 3000);` and nothing happens. Do I still have something wrong? – Yasir C Apr 19 '19 at 00:52
  • You should check the `total` variable value. – Khalid Ali Apr 19 '19 at 01:28