Skip to content

Instantly share code, notes, and snippets.

@EmperorEarth
Created August 20, 2020 03:36
Show Gist options
  • Save EmperorEarth/8eca0a968d1c433514e9bf2bd0fa32d6 to your computer and use it in GitHub Desktop.
Save EmperorEarth/8eca0a968d1c433514e9bf2bd0fa32d6 to your computer and use it in GitHub Desktop.
countdown
import React from "react";
import { Button, Text, View } from "react-native";
class App extends React.Component {
render() {
const remaining = this.state.deadline - this.state.now;
const minutes = Math.floor(remaining / 60000);
const seconds = Math.round((remaining - minutes * 60000) / 1000);
return (
<View style={{ padding: 10 }}>
{this.state.deadline !== null && (
<Text>{`${minutes}:${seconds >= 10 ? seconds : "0" + seconds}`}</Text>
)}
<Button onPress={this._onPress}>Start Timer</Button>
</View>
);
}
constructor() {
super();
this.state = {
deadline: null,
now: new Date(),
};
this._onPress = this._onPress.bind(this);
this._tick = this._tick.bind(this);
}
_onPress() {
const now = new Date();
this.setState({
deadline: now.setSeconds(now.getSeconds() + 15),
now,
});
setTimeout(this._tick, 1000);
}
_tick() {
const now = new Date();
this.setState({
now,
});
if (this.state.deadline - now < 0) {
this.setState({
deadline: null,
});
return;
}
setTimeout(this._tick, 1000);
}
}
export default App;
import React from "react";
class App extends React.Component {
render() {
const remaining = this.state.deadline - this.state.now;
const minutes = Math.floor(remaining / 60000);
const seconds = Math.round((remaining - minutes * 60000) / 1000);
return (
<div style={{ padding: 10 }}>
{this.state.deadline !== null &&
`${minutes}:${seconds >= 10 ? seconds : "0" + seconds}`}
<button onClick={this._onClick}>Start Timer</button>
</div>
);
}
constructor() {
super();
this.state = {
deadline: null,
now: new Date(),
};
this._onClick = this._onClick.bind(this);
this._tick = this._tick.bind(this);
}
_onClick() {
const now = new Date();
this.setState({
deadline: now.setSeconds(now.getSeconds() + 15),
now,
});
setTimeout(this._tick, 1000);
}
_tick() {
const now = new Date();
this.setState({
now,
});
if (this.state.deadline - now < 0) {
this.setState({
deadline: null,
});
return;
}
setTimeout(this._tick, 1000);
}
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment