Plohej Plohej - 3 months ago 24
Javascript Question

Javascript tic-tac-toe timer

I am making a tic-tac-toe game and I was proposed with idea to make a counter which would say how much time is left to make a move. Lets say 10 seconds. How to make timer which would run in background and reset each time a move is done or stop the game making a person who didn't make a move in time a looser ?
Heres my HTML :

<link rel="stylesheet" href="styles/style.css"/>
<div class="centered" id="content">
<div class="row" id="r1">
<div class="field empty" id="f1"></div>
<div class="field empty" id="f4"></div>
<div class="field empty" id="f7"></div>
<div class="row" id="r2">
<div class="field empty" id="f2"></div>
<div class="field empty" id="f5"></div>
<div class="field empty" id="f8"></div>
<div class="row" id="r3">
<div class="field empty" id="f3"></div>
<div class="field empty" id="f6"></div>
<div class="field empty" id="f9"></div>
<script type="application/javascript" src="scripts/jquery/jquery-3.1.1.min.js"></script>
<script type="application/javascript" src="scripts/scripts.js"></script>

And here's javascript/jquery :

var changeTurn = false;
var turn = true;
var classCross = "cross";
var classCircle = "circle";
var classEmpty = "empty";

$('.field').click(function(event) {
var div = $(this);
changeTurn = false;
if (turn) {
if (fieldIsFree(div)) {
changeTurn = true;
else {
if (fieldIsFree(div)) {
changeTurn = true;
if (changeTurn)
turn = !turn;
return false;

function fieldIsFree(tmpdiv) {
if (tmpdiv.hasClass(classCross))
return false;
if (tmpdiv.hasClass(classCircle))
return false;
return true;


I've implemented a very boring game that shows how you might approach this. The main thing you need to take care of is keeping track of the return value of setTimeout. This value should be used to cancel the current timeout (using clearTimeout), which you would want to do every time a player moves or if the game is paused or stopped.

"use strict";

var timer;
var button;
var timeLeft;
var label;

function countdown() {
  if (timeLeft) {
    label.innerHTML = timeLeft;
    timer = setTimeout(countdown, 1000);
  } else {
    label.innerHTML = "Fail";
    timer = undefined;

function takeMove() {
  if (typeof(timer) === "undefined") {
    button.innerHTML = "Move";
    timeLeft = 10;
  } else {
    timeLeft = 10;

function init() {
  button = document.getElementById("move");
  label = document.getElementById("label");
  button.addEventListener("click", takeMove);

document.addEventListener("DOMContentLoaded", init, false);
<div id="game-board">
  <button id="move">Start</button>
<div id="output">
  Time left: <span id="label"><span>