time.NewTimer() Function in Golang With Examples
Last Updated :
21 Apr, 2020
In Go language, time packages supplies functionality for determining as well as viewing time. The NewTimer() function in Go language is used to create a new Timer that will transmit the actual time on its channel at least after duration “d”. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions.
Syntax:
func NewTimer(d Duration) *Timer
Here, *Timer is a pointer to the Timer.
Return Value: It returns a channel that notifies how long a timer will have to wait.
Example 1:
package main
import (
"fmt"
"time"
)
func main() {
newtimer := time .NewTimer(5 * time .Second)
<-newtimer.C
fmt.Println( "Timer is inactivated" )
}
|
Output:
Timer is inactivated
Here, the above output is printed after 5 seconds of running the code, as after that stated time the channel is being notified that the timer is inactivated.
Example 2:
package main
import (
"fmt"
"time"
)
func main() {
newtimer := time .NewTimer( time .Second)
go func() {
<-newtimer.C
fmt.Println( "timer inactivated" )
}()
stoptimer := newtimer.Stop()
if stoptimer {
fmt.Println( "The timer is stopped!" )
}
time .Sleep(4 * time .Second)
}
|
Output:
The timer is stopped!
In the above method, the timer is being stopped before inactivating as here the stop method is being called to stop the timer. And at last, the program is exited using sleep method.
Share your thoughts in the comments
Please Login to comment...