Search code examples
jqueryfadeintiming

Use getTime in fadeIn function jquery


Ok, now I'm stuck for some time with this: I'm running a js script which displays words.

With some help from SO this works exactly as I want and seems much simpler than my previous attempts.

$("#stimuli").text("A WORD").fadeIn().delay(displaytime).fadeOut();}

Yet there is one issue, I want to record the time of the 'stimuli' appearance as t1, like

t1 = (new Date()).getTime();

and the time of a keypress as time t2. Is there a way to incorporate the t1 into the one-line above?


Solution

  • Do you want the time to be recorded as soon as the element starts fading in or when the fade is done?

    In the first case, just run those two lines together:

    $('#stimuli').text('A WORD').fadeIn().delay(displayTime).fadeOut();
    t1 = (new Date).getTime();
    

    fadeIn, delay, and fadeOut run asynchronously, so the second line actually happens before the other methods.

    To record the time after the fade is done, you need a callback:

    $('#stimuli')
      .text('A WORD')
      .fadeIn(function () {
        t1 = (new Date).getTime();
      })
      .delay(displayTime)
      .fadeOut();