Collapse Sidebar


This function binds a function to be called prior to the game shutting down.

Multiple functions can be bound using BindToClose if it is called repeatedly. The game will wait a maximum of 30 seconds for all bound functions to complete running before shutting down. After 30 seconds, the game will shut down regardless if all bound functions have completed or not.

Bound functions will be called in parallel, meaning they will run at the same time.

When using the DataStoreService, best practice is to bind a function saving all unsaved data to GlobalDataStore|DataStores using BindToClose. Otherwise, data may be lost if the game shuts down unexpectedly. For an example of this, see below.

You are advised to use RunService/IsStudio to verify the current session is not Roblox Studio. If this is not done, all bound functions will be required to complete in offline testing sessions.

See also

  • PluginGui/BindToClose, which is used to bind a function to a PluginGui close button and should not be confused with this function


Name Type Default Description

A function to be called prior to the game shutting down


Return Type Summary

Code Samples

Saving player data before shutting down

The following code sample is an example of how DataModel/BindToClose can be used to save player data in the event of a server shutdown. In this example, player data is stored in a dictionary named playerData with Player/UserId|UserIds as keys.

local Players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")
local RunService = game:GetService("RunService")

local dataStore = DataStoreService:GetDataStore("Data")

local playerData = {
    -- [UserId] = data

    -- if the current session is studio, do nothing
    if RunService:IsStudio() then

    print("saving player data")

    -- go through all players, saving their data
    local players = Players:GetPlayers()
    for _, player in pairs(players) do
        local userId = player.UserId
        local data = playerData[userId]
        if data then
            -- wrap in pcall to handle any errors
            local success, result = pcall(function()
                -- SetAsync yields so will stall shutdown
                dataStore:SetAsync(userId, data)
            if not success then

    print("completed saving player data")


Binding to and Handling Game Shutdown

The example below would print “4” to the output. It would wait three seconds and then print “Done”. At this point Roblox will be able to shut down the server.