2017-03-06 42 views
-1

我試圖讓定時器啓動時,鼠標按鍵時用鼠標按下功能,當鼠標按鍵時與mouseUp事件功能停止定時器上的鼠標按下()函數啓動計時器,並顯示在DIV

下面是代碼,我得到:

var startTime; 
 

 
function display() { 
 
    // later record end time 
 
    var endTime = new Date(); 
 

 
    // time difference in ms 
 
    var timeDiff = endTime - startTime; 
 

 
    // strip the miliseconds 
 
    timeDiff /= 1; 
 

 
    // get seconds 
 
    var seconds = Math.round(timeDiff % 100000000); 
 

 
    
 

 

 

 
    $(".time").text(seconds); 
 
    setTimeout(display, 1); 
 
} 
 

 
$(canvas).click(function() { 
 
    startTime = new Date(); 
 
    setTimeout(display, 1); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<canvas height="420" style="background:#e4e1e1" id="canvas" width="540"></canvas> 
 

 
<div class="time"></div>

+0

什麼是你的問題? – BenM

+0

你希望計時器停止的MouseUp? [使用JavaScript/jQuery的MOUSEDOWN定時器]的 – CaptainHere

+0

可能的複製(http://stackoverflow.com/questions/6091026/mousedown-timer-using-javascript-jquery) –

回答

0

,因爲你想要的功能重複解僱你可以使用setInterval代替setTimeout這裏。但是,無論你使用,你必須間隔的返回值賦值給一個變量,這樣就可以用clearTimeoutclearInterval晚停止。

另外,有一個最短時間的計時器將永遠無法早於調用,它大約是9-16毫秒,因此你的1毫秒的延遲永遠不會發生。

var startTime = null; 
 
var timer = null; 
 

 
function display() { 
 
    // later record end time 
 
    var endTime = new Date(); 
 

 
    // time difference in ms 
 
    var timeDiff = endTime - startTime; 
 

 
    // strip the miliseconds 
 
    timeDiff /= 1; 
 

 
    // get seconds 
 
    var seconds = Math.round(timeDiff % 100000000); 
 

 
    $(".time").text(seconds); 
 
} 
 

 
$(canvas).on("mousedown", function() { 
 
    startTime = new Date(); 
 
    timer = setInterval(display, 10); 
 
}); 
 

 
$(canvas).on("mouseup", function() { 
 
    clearInterval(timer); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<canvas height="50" style="background:#e4e1e1" id="canvas" width="100"></canvas> 
 

 
<div class="time"></div>

相關問題