MAHDI
MAHDI

Reputation: 79

can't understand the parameter after JS function

Someone wrote this function for mouse detection. But I really don't understand how it works. So I had few questions about the function.

 document.onmousemove = (function() {
  var onmousestop = function() {
    /* do stuff */
    console.log('STOP');
  }, thread;

  return function() {
 clearTimeout(thread);
    console.log(thread);
    thread = setTimeout(onmousestop, 500);
    
  };
})();

there is a part where we have function(){},thread; what does that part actually mean? What does the parameter after } of a function indicates?

Upvotes: 0

Views: 122

Answers (3)

sinbar
sinbar

Reputation: 1063

Let's step by step

(function() {
  var onmousestop = function() {
    /* do stuff */
    console.log('STOP');
  }, thread;

  return function() {
 clearTimeout(thread);
    console.log(thread);
    thread = setTimeout(onmousestop, 500);

  };
})();

That is a self-run function, which same with

function t() {
      var onmousestop = function() {
        /* do stuff */
        console.log('STOP');
      }, thread;

      return function() {
        clearTimeout(thread);
        console.log(thread);
        thread = setTimeout(onmousestop, 500);

      };
    }
t()

So the code is like:

var onmousestop = function() {
    /* do stuff */
    console.log('STOP');
};
var thread;
document.onmousemove = function() {
clearTimeout(thread);
    console.log(thread);
    thread = setTimeout(onmousestop, 500);
  };

Upvotes: 1

Rocky Sims
Rocky Sims

Reputation: 3598

var onmousestop = function() {
        /* do stuff */
        console.log('STOP');
    }, thread;

is equivalent to

var onmousestop = function() {
        /* do stuff */
        console.log('STOP');
    };
var thread;

The return function

return function() {
    clearTimeout(thread);
    console.log(thread);
    thread = setTimeout(onmousestop, 500);
};

is doing two things. 1) clearTimeout(thread); cancels any previously scheduled (and still pending) call to onmousestop. 2) thread = setTimeout(onmousestop, 500); schedules a call to onmousetop in 500ms and sets thread to what is essentially an id to identify the scheduled action (so that it can be cancelled).

Upvotes: 2

zfrisch
zfrisch

Reputation: 8660

You can declare multiple variables at once by separating them with a comma.

var a = function(){}, thread;

this means a is an empty function, and thread is declared but undefined

thread is a variable being declared within the first function returned, and then initialized within the second.

The timeout causes a recursive function call after 500 ms, where the initial function is called again.

Upvotes: 1

Related Questions