github.com/tinygo-org/tinygo@v0.31.3-0.20240404173401-90b0bf646c27/src/runtime/runtime_wasm_js.go (about)

     1  //go:build wasm && !wasip1
     2  
     3  package runtime
     4  
     5  import "unsafe"
     6  
     7  type timeUnit float64 // time in milliseconds, just like Date.now() in JavaScript
     8  
     9  // wasmNested is used to detect scheduler nesting (WASM calls into JS calls back into WASM).
    10  // When this happens, we need to use a reduced version of the scheduler.
    11  var wasmNested bool
    12  
    13  //export _start
    14  func _start() {
    15  	// These need to be initialized early so that the heap can be initialized.
    16  	heapStart = uintptr(unsafe.Pointer(&heapStartSymbol))
    17  	heapEnd = uintptr(wasm_memory_size(0) * wasmPageSize)
    18  
    19  	wasmNested = true
    20  	run()
    21  	wasmNested = false
    22  }
    23  
    24  var handleEvent func()
    25  
    26  //go:linkname setEventHandler syscall/js.setEventHandler
    27  func setEventHandler(fn func()) {
    28  	handleEvent = fn
    29  }
    30  
    31  func ticksToNanoseconds(ticks timeUnit) int64 {
    32  	// The JavaScript API works in float64 milliseconds, so convert to
    33  	// nanoseconds first before converting to a timeUnit (which is a float64),
    34  	// to avoid precision loss.
    35  	return int64(ticks * 1e6)
    36  }
    37  
    38  func nanosecondsToTicks(ns int64) timeUnit {
    39  	// The JavaScript API works in float64 milliseconds, so convert to timeUnit
    40  	// (which is a float64) first before dividing, to avoid precision loss.
    41  	return timeUnit(ns) / 1e6
    42  }
    43  
    44  // This function is called by the scheduler.
    45  // Schedule a call to runtime.scheduler, do not actually sleep.
    46  //
    47  //go:wasmimport gojs runtime.sleepTicks
    48  func sleepTicks(d timeUnit)
    49  
    50  //go:wasmimport gojs runtime.ticks
    51  func ticks() timeUnit