D
D
Daniil Igorevich2016-02-02 19:40:45
JavaScript
Daniil Igorevich, 2016-02-02 19:40:45

Why was the result of the function not returned after a certain number of milliseconds?

function f(x) {
  alert( x );
}
function delay(f, ms){
  return function(arg){
    return setTimeout(f(arg), ms);
  }
}

var f1000 = delay(f, 3000);
var f1500 = delay(f, 5500);

f1000("тест"); 
f1500("тест2");

I run it and both 'test1' and 'test2' come back immediately, what's the problem?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Peter, 2016-02-02
@petermzg

What did you want to get?
You have a direct call to f(arg); here is alert

K
Kovalsky, 2016-02-02
@lazalu68

To defer execution and pass an argument, you need to do something like this:

function f(x) {
  alert( x );
}
function delay(f, ms){
  return function(arg){
    return setTimeout(function() { return f(arg); }, ms);
  }
}

var f1000 = delay(f, 3000);
var f1500 = delay(f, 5500);

f1000("тест"); 
f1500("тест2");

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question