0

I want to make a loop that downloads a file on an interval. But I can't make the setTimeout function work when the request function needs a parameter. It's the last line of the progam that i failing. What am I doing wrong?

const http = require('http');
const fs = require('fs');

const file = fs.createWriteStream("file.jpg");
const fileToDownload = "http://i3.ytimg.com/vi/J---aiyznGQ/mqdefault.jpg";

function request1() {
        http.get(fileToDownload, function(response) {
                response.pipe(file)
        });
}

function request2(saveName) {
        const save = fs.createWriteStream(saveName);

        http.get(fileToDownload, function(response) {
                response.pipe(save)
        });
}

setTimeout(request1, 3000);
setTimeout(request2("file2.jpg"), 3000); // TypeError: "callback" argument must be a function 
Kasper Hansen
  • 6,307
  • 21
  • 70
  • 106
  • You're passing the value *returned* by making a function call to `request2()`. – Pointy Oct 21 '19 at 12:18
  • First find on google : [setTimeout - callback argument must be a function](https://stackoverflow.com/questions/51685383/settimeout-callback-argument-must-be-a-function/51685407)) :( – Mara Black Oct 21 '19 at 12:21

3 Answers3

3

You're not passing a function, rather its result. Use the following instead:

setTimeout(() => request2("file2.jpg"), 3000);
Arik
  • 5,266
  • 1
  • 27
  • 26
2

Instead of passing a function to the setTimeout as it expects, you're passing a function call, which will take the parameter as the return type of the function instead of the function itself.

Instead you can just pass a function like -

setTimeout(() => request2("file2.jpg"), 3000);
Vandesh
  • 6,368
  • 1
  • 26
  • 38
2

Instead of calling function directly, try this:

setTimeout(function(){
  request2("file2.jpg")
}, 3000);

Or using arrow function

setTimeout(() => request2("file2.jpg"), 3000)
Sagar Jajoriya
  • 2,377
  • 1
  • 9
  • 17