xhr: respect 50ms min delay between two progress events

This commit is contained in:
Pierre Tachoire
2024-02-15 17:47:32 +01:00
parent 10777a7b46
commit 5439a37d25

View File

@@ -168,6 +168,8 @@ pub const XMLHttpRequest = struct {
payload: ?[]const u8 = null, payload: ?[]const u8 = null,
const min_delay: u64 = 50000000; // 50ms
pub fn constructor(alloc: std.mem.Allocator, loop: *Loop) !XMLHttpRequest { pub fn constructor(alloc: std.mem.Allocator, loop: *Loop) !XMLHttpRequest {
return .{ return .{
.alloc = alloc, .alloc = alloc,
@@ -301,6 +303,7 @@ pub const XMLHttpRequest = struct {
typ: []const u8, typ: []const u8,
opts: ProgressEvent.EventInit, opts: ProgressEvent.EventInit,
) void { ) void {
log.debug("dispatch progress event: {s}", .{typ});
var evt = ProgressEvent.constructor(typ, .{ var evt = ProgressEvent.constructor(typ, .{
// https://xhr.spec.whatwg.org/#firing-events-using-the-progressevent-interface // https://xhr.spec.whatwg.org/#firing-events-using-the-progressevent-interface
.lengthComputable = opts.total > 0, .lengthComputable = opts.total > 0,
@@ -450,6 +453,7 @@ pub const XMLHttpRequest = struct {
const reader = self.req.?.reader(); const reader = self.req.?.reader();
var buffer: [1024]u8 = undefined; var buffer: [1024]u8 = undefined;
var ln = buffer.len; var ln = buffer.len;
var prev_dispatch: ?std.time.Instant = null;
while (ln > 0) { while (ln > 0) {
ln = reader.read(&buffer) catch |e| { ln = reader.read(&buffer) catch |e| {
buf.deinit(self.alloc); buf.deinit(self.alloc);
@@ -461,7 +465,13 @@ pub const XMLHttpRequest = struct {
}; };
loaded = loaded + ln; loaded = loaded + ln;
// TODO dispatch only if 50ms have passed. // Dispatch only if 50ms have passed.
const now = std.time.Instant.now() catch |e| {
buf.deinit(self.alloc);
return self.onErr(e);
};
if (prev_dispatch != null and now.since(prev_dispatch.?) < min_delay) continue;
defer prev_dispatch = now;
self.state = LOADING; self.state = LOADING;
self.dispatchEvt("readystatechange"); self.dispatchEvt("readystatechange");