Avoid "Watchdog Tripped Error - Code Executed Too Long"

Hello,

I wrote a recursive program, but before it finishes it crashes with the error. Is it possible to prevent that? With treeDepth 1 it works, but with 2 or more it crashed.

function alphabeta(tempBoard, player, treeDepth, alpha, beta) {
		var tempWinner = checkWin(tempBoard);
		if (movesLeft(tempBoard) == 0 || tempWinner || treeDepth == 0) {
			if (tempWinner == getEnemy(activePlayer)) {
				return -1;
			}
			if (tempWinner == 0) {
				return 0;
			}
			if (tempWinner == activePlayer) {
				return 1;
			}
			return -2;
		}
		if (treeDepth == -1) {
			treeDepth = movesLeft(tempBoard);
		}
		treeDepth--;
		for (var i=0; i<9; i++) {
			if (tempBoard[i] == 0) {
				tempBoard[i] = player;
				var results = alphabeta(tempBoard, getEnemy(player), treeDepth, -2, 2);
				tempBoard[i] = 0;
				if (player == activePlayer) {
					if (results > alpha) {
						alpha = results;
					}
            		if (alpha >= beta) {
						return beta;
					}
				} else {
					if (results < beta) {
						beta = results;
					}
            		if (beta <= alpha) {
						return alpha;
					}
				}
			}
		}
		if (player == activePlayer) {
			return alpha;
		} else {
			return beta;
		}
	}

	function computerMove(tempBoard, player) {
		var result;
		var bestMove = -2;

		if (movesLeft(tempBoard) == 9) {
			setMarker(4);
			return;
		}

		var choices = [];

		for (var i=0; i<9; i++) {
			if (tempBoard[i] == 0) {
				tempBoard[i] = player;
				var results = alphabeta(tempBoard, getEnemy(player), 2, -2, 2);
				tempBoard[i] = 0;
				if (results > bestMove) {
					bestMove = results;
					choices = [];
					choices.add(i);
				} else if (results == bestMove)  {
					choices.add(i);
				}
			}
		}
		// ToDo: Shuffle List
		setMarker(choices[0]);
	}

  • The error indicates you executed too long without returning to the vm.

    You'd see the same with something like

    var j=0;

    for(var i=0;i<1000000;i++) {

      j++;

    }

    There's no way to extend the watchdog, but you could use a timer and run bits at a time with retuns to the vm.

  • Thanks for the answer. But I don't kown how to rewrite the code with timers...

  • Then you need to rewrite your code so what you are doing won't trigger the watchdog.  The watchdog counts the number of instructions executed before returning to the system, and when the limit is hit, the watchdog timer is triggered and your app terminates.  It's to prevent any app from dominating the system.  Consider the case of an infinite loop that would run forever.  It's the system protecting itself.