我一直在尝试找出如果在javascript中调用或执行另一个函数时如何停止一个函数,我开始认为这是不可能的,希望您可以改变主意。
具体地说,我正在回调函数中使用计时器:
function endMatch(){
// Calculate points
$("#points").val(touchs*100+seconds*500);
$("#seconds").val(seconds);
//stop timer
// or all ships sunk)
clearInterval(seconds);
// Show Dialog to save points
$.afui.clearHistory();
$.afui.loadContent("#form",false,false,"up");
//disable board
}
这是我要停止的功能,以便用户在比赛结束后无法继续播放:
function shoot(celd, i, j){
switch (board[i][j]) {
case 'a':
board[i][j]= 'A';
$('#'+celd).removeClass('water');
$('#'+celd).addClass('miss')
break;
case 'b':
board[i][j]= 'B';
$('#'+celd).removeClass('water');
$('#'+celd).addClass('boats')
touchs=touchs+1;
break;
case 'd':
board[i][j]= 'd';
$('#'+celd).removeClass('water');
$('#'+celd).addClass('boats')
touchs=touchs+1;
break;
case 'f':
board[i][j]= 'F';
$('#'+celd).removeClass('water');
$('#'+celd).addClass('boats')
touchs=touchs+1;
break;
case 'p':
board[i][j]= 'P';
$('#'+celd).removeClass('water');
$('#'+celd).addClass('boats')
touchs=touchs+1;
break;
case 's':
board[i][j]= 'S';
$('#'+celd).removeClass('water');
$('#'+celd).addClass('boats')
touchs=touchs+1;
break;
}
}
在此处调用拍摄功能:
function createBoardjQ(){
$("#match").empty();
var table = $("<table />");
for(var i=0; i<rows; i++){
var row = $("<tr/>");
for(var j=0; j<columns; j++){
var celd = $('<td id="celd_'+i+'_'+j+'" onclick=shoot("celd_'+i+'_'+j+'",'+i+','+j+') > </td>');
celd.addClass("water");
row.append(celd);
}
table.append(row);
}
$("#match").append(table);
}
在此处调用了回调:
function createMatch(){
//create a matrix row x col
board = createMatrix(rows,columns);
//fill matrix "a"
startMatrix('a',board);
touchs = 0;
setBoats(board);
createBoardjQ();
seconds = 15000;
setInterval(callbackTimer, 1000);
//ADD SECONDS TO MATCH TIMER
//START TIMER with setInterval()
//Overturn matrix to console
matrix2console(board);
}
function callbackTimer(){
seconds=seconds-1000;
if(seconds===0||touchs===17){
alert("The match has ended");
endMatch();
savePoints();
}
//if time <=0 stop clearInterval() timer and end match.
}
答案 0 :(得分:1)
例如,看看以下片段:
var EXIT_FLAG = false;
function stopExecution()
{
EXIT_FLAG = true;
}
var timer = setInterval(function(){
var span = document.getElementById('timer');
if ( EXIT_FLAG )
{
clearInterval(timer);
span.innerHTML = 'stopped!';
return;
}
span.innerHTML = String(parseInt(span.innerHTML)+1);
}, 1000);
<button onclick="stopExecution()">Stop Execution<button>
<span id="timer">0</span>
调整代码段以适合您的情况。