Skip to content

MathiasWP/svelte-idle

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

22 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Features | Demo

No dependencies — TypeScript — SSR support — Readable store for idle value — onIdle callback

Installation

npm i svelte-idle -D

Usage

<script>
import { listen, idle, onIdle } from 'svelte-idle'

// Run listen on component initialization
listen()

// Run code when the user idle via a callback...
onIdle(() => {
    console.log('User is idle')
})

//... or by using the idle store
$: {
    if($idle) console.log('User is idle')
}
</script>

User is idle: {$idle}

API

listen

The listen method accepts an optional object (type: SvelteIdleListenConfig). The following values can be defined:

timer

  • type: number
  • defines: amount of milliseconds until idle is true
  • default: 60_000 (10 minutes)

cycle

  • type: number
  • defines: amount of milliseconds before each idle-check
  • default: 200

Example:

import { listen } from 'svelte-idle'

listen({
    timer: 60_000,
    cycle: 500
})

idle

A readable store that reflects the current idle-state.

onIdle

Callback which will be fired everytime idle becomes true. Returns a method for clearing the listener.

Example:

import { onMount } from 'svelte'
import { onIdle } from 'svelte-idle'

onMount(() => {
    const unsub = onIdle(() => console.log('User is idle!'))
    return unsub
})

updateOptions

Can be used if you want to update the current options set.

stopCountdown

Completely stops the countdown.

restartCountdown

Will stop the current countdown and restart it.

Example

import { onMount } from 'svelte'
import { listen, updateOptions, stopCountdown, restartCountdown } from 'svelte-idle'

/**
 * Timer is quote long
 */
listen({
    timer: 100_000,
    cycle: 500
})

/**
 * Decrease the timer
 */
updateOptions({
    timer: 10_000
})

/**
 * Stop the countdown, we don't want to count down anymore
 */
stopCountdown()

/**
 * Restart the countdown, we want to count down again
 */
restartCountdown()