@@ -14,12 +14,37 @@ let questionCounter = 0
14
14
let availableQuestions = { }
15
15
16
16
let questions = [ ]
17
+ let reloads = sessionStorage . getItem ( 'reloads' ) ? parseInt ( sessionStorage . getItem ( 'reloads' ) ) : 0
18
+
19
+ const fetchQuestions = ( ) => {
20
+
21
+ const fetchTimeout = setTimeout ( ( ) => {
22
+ if ( reloads < 3 ) {
23
+ reloads ++
24
+ sessionStorage . setItem ( 'reloads' , reloads )
25
+ window . location . reload ( )
26
+ } else {
27
+ console . error ( 'Max reload attempts reached. Unable to fetch questions.' )
28
+ }
29
+ } , 10000 ) ;
30
+
31
+
32
+
17
33
fetch ( "https://opentdb.com/api.php?amount=10&category=9&difficulty=easy&type=multiple" )
18
34
. then ( res => {
35
+ clearTimeout ( fetchTimeout ) ;
19
36
return res . json ( )
20
37
} )
21
38
. then ( loadedQuestions => {
22
- console . log ( loadedQuestions )
39
+ // console.log(loadedQuestions)
40
+ if ( ! loadedQuestions . results || loadedQuestions . results . length === 0 ) {
41
+ throw new Error ( "No Questions received" )
42
+ }
43
+
44
+ reloads = 0 // resetting to 0, if loadedQuestions received
45
+ sessionStorage . setItem ( 'reloads' , reloads )
46
+
47
+
23
48
questions = loadedQuestions . results . map ( loadedQuestion => {
24
49
const formattedQuestion = {
25
50
question : loadedQuestion . question
@@ -39,16 +64,25 @@ fetch("https://opentdb.com/api.php?amount=10&category=9&difficulty=easy&type=mul
39
64
40
65
return formattedQuestion
41
66
} )
67
+
68
+
42
69
startGame ( )
43
70
} ) . catch ( err => {
44
- ( ) => sessionStorage . clear ( )
45
- // Check if the page has already been reloaded
46
- if ( ! sessionStorage . getItem ( 'reloaded' ) ) {
71
+ clearTimeout ( fetchTimeout )
72
+ console . error ( "Error fetching questions:" , err )
73
+
74
+ if ( reloads < 3 ) {
75
+ reloads ++
76
+ sessionStorage . setItem ( 'reloads' , reloads )
47
77
window . location . reload ( )
48
- sessionStorage . setItem ( 'reloaded' , 'true' ) ;
49
- // //this flag is set as an indicator of reload
50
- }
51
- } )
78
+ } else {
79
+ console . error ( "Max reload attempts reached. Unable to fetch questions." ) ;
80
+ }
81
+
82
+ } ) ;
83
+ }
84
+
85
+ fetchQuestions ( )
52
86
53
87
//CONSTANTS
54
88
const CORRECT_BONUS = 10
0 commit comments