Implement timeout

Please merge #367 before this.