Skip to content

Commit

Permalink
Handle thundering herd of setInterval (#4109)
Browse files Browse the repository at this point in the history
Co-authored-by: Jarred Sumner <709451+Jarred-Sumner@users.noreply.github.com>
  • Loading branch information
Jarred-Sumner and Jarred-Sumner committed Aug 11, 2023
1 parent 7af3f14 commit 66da021
Showing 1 changed file with 17 additions and 2 deletions.
19 changes: 17 additions & 2 deletions src/bun.js/api/bun.zig
Original file line number Diff line number Diff line change
Expand Up @@ -3597,9 +3597,14 @@ pub const Timer = struct {
break :brk true;
}
} else {
if (map.get(this.id)) |tombstone_or_timer| {
if (map.getPtr(this.id)) |tombstone_or_timer| {
// Disable thundering herd of setInterval() calls
if (tombstone_or_timer.* != null) {
tombstone_or_timer.*.?.has_scheduled_job = false;
}

// .refresh() was called after CallbackJob enqueued
break :brk tombstone_or_timer == null;
break :brk tombstone_or_timer.* == null;
}
}

Expand Down Expand Up @@ -3869,6 +3874,7 @@ pub const Timer = struct {
did_unref_timer: bool = false,
poll_ref: JSC.PollRef = JSC.PollRef.init(),
arguments: JSC.Strong = .{},
has_scheduled_job: bool = false,

pub const Kind = enum(u32) {
setTimeout,
Expand Down Expand Up @@ -3906,6 +3912,12 @@ pub const Timer = struct {

var globalThis = this.globalThis;

// Disable thundering herd of setInterval() calls
// Skip setInterval() calls when the previous one has not been run yet.
if (repeats and this.has_scheduled_job) {
return;
}

var cb: CallbackJob = .{
.callback = if (repeats)
JSC.Strong.create(
Expand Down Expand Up @@ -3950,6 +3962,9 @@ pub const Timer = struct {
this.arguments = .{};
map.put(vm.allocator, timer_id.id, null) catch unreachable;
this.deinit();
} else {
this.has_scheduled_job = true;
map.put(vm.allocator, timer_id.id, this) catch {};
}

var job = vm.allocator.create(CallbackJob) catch @panic(
Expand Down

0 comments on commit 66da021

Please sign in to comment.