简体   繁体   中英

JavaScript - execute a task after setTimeout depending on a value

Hi have to execute two different tasks (executing PHP files) depending on how much time t I leave the mouse button clicked over an image. The events I am handling are onmousedown and onmouseup .

If t < 500 ms, execute task #1, otherwise execute task #2.

So, based on my basic JavaScript knowledge, I wrote this code:

var lastTime = 0;
var now = 0;
var tmptimer = 0;
var mousedown = false;

/* to be executed from onmousedown event */
function tsMouseDown(angleH, angleV)
{
  var angleH2 = parseFloat(angleH);
  var angleV2 = parseFloat(angleV);
  var div = document.getElementById("debugDiv");
  div.textContent = 'tsMouseDown: ' + angleH + " - " + angleV + ' - ';

  mousedown = true;
  lastTime = new Date().getTime();
  tmptimer = setTimeout( function(){ ;}, 500);
  div.textContent = 'tsMouseDown: ' + angleH2 + " - " + angleV2 + ' - ' + tmptimer +  ' - ' + mousedown;

  /* 
     try to execute task #1 or #2 depending on mousedown value
     (!) DOES NOT WORK 
  */
  if(mousedown == false)
  {
    $("#content").load("task1.php",{ /* args here ... */ });
  } 
  else if(mousedown == true)
  {
    $("#content").load("task2.php",{ /* args here ... */ });
  }
}

/* to be executed from onmouseup event */
function tsMouseUp()
{
  mousedown = false;
  clearTimeout(tmptimer);
  tmptimer = -1;
  var div = document.getElementById("debugDiv");

  now = new Date().getTime();

  if((now - lastTime) < 500))
    div.textContent = "tsMouseUp: " + (now - lastTime) + "< 500 ms - "  + tmptimer + ' -' + mousedown;  
  else
    div.textContent = "tsMouseUp: " + (now - lastTime) + "> 500 ms"  + tmptimer + ' -' + mousedown;  
}

The code works fine recognizing how much time the mouse button remains clicked, but the condition for mousedown variable in the function tsMouseDown is never evaluated as I would like to, becuase task2.php is always executed, even if tsMouseUp is executed before the timeout.

What's the better way to solve this situation? How do I have to change my code to make it work ?

Thank you in advance.

A bit clearer is to bind the events on to each other.. for example:

var longTouch = false;
$(this).mousedown(function() {
    timeout = setTimeout(function() {
        longTouch = true;
    }, 500);
}).mouseup(function() {
    clearTimeout(timeout);
    if (longTouch && longTouch == true) {
        // do whatever you want if it was longer than 500ms
    } else {
        //else do click actions
    }          
});
longTouch = false;

This way around the mouseup event interrupts the mousedown or if it was longer than the interval specified then it does the other action. I hope it's clear enough.

I've made a jsFiddle to demonstrate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM