68 lines
1.9 KiB
JavaScript
68 lines
1.9 KiB
JavaScript
import React, { useEffect, useState, useRef } from 'react'
|
|
import mediator from '../../util/mediator'
|
|
|
|
function padLeft(s) {
|
|
return s.toString().padStart(2, '0')
|
|
}
|
|
function getTimer(sec) {
|
|
const minuts = Math.floor(sec / 60)
|
|
const second = sec % 60
|
|
const hour = Math.floor(minuts / 60)
|
|
return `${padLeft(hour)}:${padLeft(minuts - hour * 60)}:${padLeft(second)}`
|
|
}
|
|
|
|
//评测计时
|
|
//identifier taskId
|
|
export default ({ identifier, onUpdateCostTime, status, defaultTime = 0,type }) => {
|
|
|
|
const [costTime, setCostTime] = useState(defaultTime)
|
|
const lastV = useRef(defaultTime)
|
|
|
|
useEffect(() => {
|
|
lastV.current = defaultTime
|
|
setCostTime(defaultTime)
|
|
//已经评测完成的不需要再计时
|
|
|
|
if (status !== 2) {
|
|
let timeHandler = function () {
|
|
setCostTime(costTime => costTime + 1)
|
|
lastV.current = lastV.current + 1
|
|
}
|
|
let tid = window.setInterval(timeHandler, 1000)
|
|
let unSub = mediator.subscribe('update-cost-time', () => {
|
|
onUpdateCostTime(identifier, { time: lastV.current }).then(() => {
|
|
mediator.publish('reset-game')
|
|
})
|
|
})
|
|
return () => {
|
|
clearInterval(tid)
|
|
unSub()
|
|
|
|
|
|
if(type===1){
|
|
let bodys = {
|
|
answer_long_time: lastV.current*1000,
|
|
};
|
|
let headers = {
|
|
type: 'application/json',
|
|
};
|
|
let blob = new Blob([JSON.stringify(bodys)], headers);
|
|
window.navigator.sendBeacon(
|
|
`https://test-data.educoder.net/api/myproblems/${identifier}/save_long_time.json?answer_long_time=${lastV.current*1000}`,
|
|
blob,
|
|
);
|
|
mediator.publish('reset-game')
|
|
return
|
|
}
|
|
onUpdateCostTime(identifier, { time: lastV.current }).then(() => {
|
|
mediator.publish('reset-game')
|
|
})
|
|
}
|
|
}
|
|
}, [identifier, onUpdateCostTime, status, defaultTime])
|
|
|
|
|
|
return (
|
|
<span>{getTimer(costTime)}</span>
|
|
)
|
|
} |